2012-12-20 39 views

回答

11

代孕是Backbone中的「助手」類,用於設置原型鏈。查看源代碼:

// Helper function to correctly set up the prototype chain, for subclasses. 
    // Similar to `goog.inherits`, but uses a hash of prototype properties and 
    // class properties to be extended. 
    var extend = function(protoProps, staticProps) { 
    var parent = this; 
    var child; 

    // The constructor function for the new subclass is either defined by you 
    // (the "constructor" property in your `extend` definition), or defaulted 
    // by us to simply call the parent's constructor. 
    if (protoProps && _.has(protoProps, 'constructor')) { 
     child = protoProps.constructor; 
    } else { 
     child = function(){ parent.apply(this, arguments); }; 
    } 

    // Add static properties to the constructor function, if supplied. 
    _.extend(child, parent, staticProps); 

    // Set the prototype chain to inherit from `parent`, without calling 
    // `parent`'s constructor function. 
    var Surrogate = function(){ this.constructor = child; }; 
    Surrogate.prototype = parent.prototype; 
    child.prototype = new Surrogate; 

    // Add prototype properties (instance properties) to the subclass, 
    // if supplied. 
    if (protoProps) _.extend(child.prototype, protoProps); 

    // Set a convenience property in case the parent's prototype is needed 
    // later. 
    child.__super__ = parent.prototype; 

    return child; 
    }; 
+0

謝謝你的回答。你/有人知道:「避免在這裏調用父母的構造函數?」的願望或理由是什麼? – humanityANDpeace

+1

@humanityANDpeace,沒有Surrogate的構造函數會在克隆時啓動parent.prototype - > child.prototype = new parent(); 那麼當你實例化你的孩子時,父母的構造函數會被再次調用。所以Surrogate的目的是避免重複的構造函數調用。 –