What does the new
keyword do that allows the following binding on the this
object:
function Person(first, last) {
this.first = first;
this.last = last;
}
Person.prototype.greet = function() {
console.log(`Hello, ${this.first} ${this.last}.`);
};
let p = new Person('Tom', 'Jones');
p.greet();
Whereas without the new
keyword, this.first
would raise an error since it is undefined. Conceptually speaking, what is new
doing here in how it modifies the function?
Without new
:
function Person(first, last) {
this.first = first;
this.last = last;
}
Person('Tom', 'Jones');
// TypeError: Cannot set property 'first' of undefined
And without using new
seems the following is a crude way to simulate it:
function Person(first, last) {
this.first = first;
this.last = last;
return this;
}
Person.prototype.greet = function() {
console.log(`Hello, ${this.first} ${this.last}.`);
};
Person.prototype.greet.call(Person.call({}, 'Tom', 'Jones'));