Prototypal inheritance and new keyword

前端 未结 2 1232
感情败类
感情败类 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.

    0 讨论(0)
  • 2020-12-21 14:36

    This is a script that describes the above situation

    var x = {
        // do nothing
    };
    
    var a = function() {};
    
    a.prototype = x;
    
    var b = new a();
    console.log("b.__proto__ is x? " + (b.__proto__ == x)); // true
    
    var c = function() {};
    c.prototype = new a();
    console.log("c prototype.__proto__ is x? " + (c.prototype.__proto__ == x)); // true
    
    var anotherFn = function() {
        // do nothing
    };
    c.prototype.aFn = anotherFn;
    
    var d = new c();
    console.log("d __proto__^2 is x?" + (d.__proto__.__proto__ == x)); // true
    console.log("d __proto__.aFn is anotherFn? " + (d.__proto__.aFn == anotherFn)); // true
    
    0 讨论(0)
提交回复
热议问题