Prototypal inheritance and new keyword

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

提交回复
热议问题