What are the role of Constructor in class of JavaScript?

0 votes
32 views
Ravi Vishwakarma asked 10 days ago in Web Application by Ravi Vishwakarma

What are the role of Constructor in class of JavaScript?

1 Answer

0 votes
Ethan Karla answered 7 days ago by Ethan Karla
JavaScript is an object oriented script language. So in this language apply the class and object pattern. In object oriented technique use class. In class we can define the variable, constructor, get and set property, method. Constructor is special type of function in JavaScript. This is invoke when class object are created in JavaScript. In JavaScript constructor are two type – default and parameterizes constructor. This is used to make constructor function.
The constructor method is a special method:
• It has to have the exact name 'constructor'
• It is executed automatically when a new object is created
• It is used to initialize object properties
If you do not define a constructor method, JavaScript will add an empty constructor method.
Syntax:
class class-name [extends parent-class]{

 constructor (arguments1, argument2, ----){
  // super();
  // initialize the field
 }
 // other statement
}
Example:
class Car {

 constructor(name, year) {
     this.name = name;
     this.year = year;
   }
}
<!DOCTYPE html>

<html lang='en' xmlns='http://www.w3.org/1999/xhtml'>
    <head>
    <meta charset='utf-8' />
    <title></title>
</head>
<body>
<h2>JavaScript Class Method</h2>
<p>How to define and use a Class method.</p>
<p id='demo'></p>
<script>
class Person {
    //constructor
    constructor(name, year) {
        this.name = name;
        this.year = year;
    }
    //fucntion
    age() {
        let date = new Date();
        return date.getFullYear() - this.year;
    }
}
    let person = new Person('MindStick', 2010);
    document.getElementById('demo').innerHTML ='My name is '+person.name+' and i am ' + person.age() + ' years old.';
</script>
</body>
</html>
Constructor function
// constructor function

function Person () {
    this.name = 'John',
    this.age = 23,
     this.greet = function () {
        console.log('hello');
    }
}
// create objects
const person1 = new Person();
const person2 = new Person();
// access properties
console.log(person1.name); // John
console.log(person2.name); // John