Careeroza
Constructor Functions
Before Classes
Example
Before ES6, "classes" were functions called with new; shared methods were put on Function.prototype:
function Person(name) {
this.name = name;
}
Person.prototype.greet = function () {
return "Hi, I am " + this.name;
};
const p1 = new Person("Asha");
const p2 = new Person("Vikram");
console.log(p1.greet(), p2.greet());
console.log(p1.greet === p2.greet); // one shared methodOutput
Hi, I am Asha Hi, I am Vikram true
What new Does
- Creates a new empty object.
- Sets its prototype to
Constructor.prototype. - Calls the constructor with
this= the new object. - Returns the object (unless the constructor returns another object).