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