In JavaScript, a constructor is a function that is used to create and initialize an object created with the new
keyword. When the new
keyword is used with this function, a new object is created with the properties.
JavaScript constructor example
Simple HTML example code.
<!DOCTYPE html>
<html>
<body>
<script >
function Person(name, age) {
this.name = name;
this.age = age;
}
let p1 = new Person('John', 30);
console.log(p1)
console.log(typeof(p1))
</script>
</body>
</html>
Output:
Constructors can also be defined using class syntax, introduced in ECMAScript 2015 (ES6):
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
}
let p1 = new Person('John', 30);
In this case, the Person
class has a constructor method that is called when a new object is created with the new
keyword. The constructor initializes the name
and age
properties of the new object.
Do comment if you have any doubts or suggestions on this JS constructor topic.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version