0
What are the role of Constructor in class of JavaScript?
What are the role of Constructor in class of JavaScript?
class class-name [extends parent-class]{
constructor (arguments1, argument2, ----){
// super();
// initialize the field
}
// other statement
}
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
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