Constructor Functions in JavaScript
A constructor function is a function used as a blueprint to create many similar objects. By habit its name starts with a capital letter, and you call it with the new keyword.
function Person(name, age) {
this.name = name;
this.age = age;
this.greet = function () {
return "Hi, I am " + this.name;
};
}
const p1 = new Person("Robin", 25);
const p2 = new Person("Maria", 30);
console.log(p1.name);
console.log(p2.greet());
Output of the above program is
Robin
Hi, I am Maria
What does new do?
- Creates a new empty object.
- Sets
thisinside the function to that object. - Runs the function body, which adds properties to
this. - Returns the object.
Shared methods with prototype
In the example above, every object gets its own copy of greet, which wastes memory. Put shared methods on the prototype, and all objects use the same function.
function Person(name) {
this.name = name;
}
Person.prototype.greet = function () {
return "Hi, I am " + this.name;
};
const p1 = new Person("Robin");
const p2 = new Person("Maria");
console.log(p1.greet());
console.log(p1.greet === p2.greet);
Output of the above program is
Hi, I am Robin
true
instanceof
console.log(p1 instanceof Person);
console.log(p1.constructor === Person);
Output of the above program is
true
true
Note:
Forgetting new is a common mistake. Then this is not a new object and the properties are set on the wrong thing. Modern code uses classes, which give an error if you forget new.
Summary
- A constructor function is a blueprint, called with
new. - Use
thisto set properties, and the prototype for shared methods. - Classes are the modern syntax for the same idea.
- Next: The this keyword.
Congratulations! Chapter Finished. Learn more about the similar topics:
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |