Effective [removed] Making your Constructor Function new-agnostic

前端 未结 2 932
青春惊慌失措
青春惊慌失措 2020-12-11 21:33

I\'ve been reading \'Effective JavaScript\' lately and I came across this question.

The author explains how it\'s important to make your Constructor Function new-ag

相关标签:
2条回答
  • 2020-12-11 22:08

    Yes, the effect is the same, however, it allocates one more object. The constructor is meant to be used with new, and this technique takes car of the cases where the programmer has forgotten the new.

    It would be better to throw an exception in the latter case if you ask me.

    0 讨论(0)
  • 2020-12-11 22:22

    Why worry about 'this' and 'new' at all and why not always just create our constructors like the one above?

    Because it is just more concise to write only

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

    new was invented before Object.create (which is not available in older browsers) and became the standard pattern. Most people are so accustomed to it that they don't bother to include a if (!(this instanceof Person)) return new Person(name, age) check.

    If you're setting up a new Object that does the same thing as 'this', can't we just never worry about if the constructor was called with new by foregoing 'this' and just creating the new object.

    No, you don't always know how to create the new object. this instanceof Person is also true for anything else that does inherit from Person.prototype, and does allow for class inheritance:

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

    The Person.call(this) wouldn't be possible if you chose to always return a new object.

    0 讨论(0)
提交回复
热议问题