Prototypal inheritance and new keyword

前端 未结 2 1248
感情败类
感情败类 2020-12-21 13:36

In backbone.js under the inherits method, the authors does this:

var ctor = function() {};
// some other code ...

var child;
// some other code ...
ctor.pro         


        
2条回答
  •  无人及你
    2020-12-21 14:29

    Remember that a prototype is an instance of the parent type. Using child.prototype = parent.prototype would set the child's prototype equal to the parent's prototype, rather than an prototypical instance of the parent.

    Here's a huge problem that arises if you use child.prototype = parent.prototype: if you try to alter the child's prototype, you're also altering the parent's prototype, because they are the same object.

    Child.prototype.childOnlyValue = 5;
    // WARNING: Parent.prototype.childOnlyValue is now also 5,
    //             because Parent.prototype === Child.prototype
    

    Creating the new instance of the parent is absolutely necessary. Otherwise, you'll have a flat prototype chain with a single shared prototype, so you'll have problems like the one I've outlined above.

提交回复
热议问题