I've been reading Effective JavaScript lately and I stumbled upon this question.
The author explains how important it is to make your constructor-function new-agnostic, because if the developer forgets to call the constructor with the keyword "new", this refers to the window. It makes sense. I am confused by the goal of its implementation.
He advises setting up your constructor as follows.
var Person = function(name, age){
var that = this instanceof Person ? this : Object.create(Person.prototype);
that.name = name;
that.age = age;
return that;
}
It makes sense. You check if 'this' is an instance of Person, that is, it was called with the keyword "new". If this is not the case, create a new object that will do the same as 'this' and return that object.
My question is that. If you create a new object that does the same thing as 'this', can't we just not worry about whether the constructor was called with a new one by specifying 'this' and just creating a new object.
var Person = function(name, age){
var that = Object.create(Person.prototype);
that.name = name;
that.age = age;
return that;
}
Why worry about 'this' and 'new' in general, and why is it not always easy to create our constructors like the ones above?
source
share