Effective JavaScript: creating a new-agnostic constructor function

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?

+4
source share
2 answers

Why worry about 'this' and 'new' in general, and why is it not always easy to create our constructors like the ones above?

Because it’s just more concise to write only

function Person(name, age) {
    this.name = name;
    this.age = age;
}

newwas invented before Object.create(which is not available in older browsers) and became the standard template. Most people are so used to it that they don’t bother checking if (!(this instanceof Person)) return new Person(name, age).

, , 'this', , , 'this' .

, , . this instanceof Person , Person.prototype :

function Employee(name, age, salary) {
    Person.call(this, name, age);
    this.salary = salary;
}
Employee.prototype = Object.create(Person.prototype);

Person.call(this) , .

+6

, , . , , .

, .

-1

Source: https://habr.com/ru/post/1543096/


All Articles