2012-12-20 11 views
8

Backbone.js का उपयोग करके, __proto__ सरोगेट होने के लिए टाइप करने के लिए कंसोल ने Backbone.View.extend({}) का एक उदाहरण लॉग किया।जावास्क्रिप्ट में __proto__ प्रकार सरोगेट क्या है?

var view = Backbone.View.extend({}); 
console.log(view); 

इस के लिए प्रकार सरोगेट के साथ एक वस्तु के परिणामस्वरूप अपनी __proto__

__proto__: Surrogate 

सरोगेट क्या है?

उत्तर

11

सरोगेट प्रोटोटाइप चेनिंग सेट अप करने के लिए बैकबोन में एक "सहायक" वर्ग है। स्रोत कोड देखें:

// 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

@ सुमानींडैंडेस, सरोगेट के कन्स्ट्रक्टर के बिना माता-पिता क्लोनिंग करते समय शुरू होगा .prototype -> child.prototype = new parent(); तब जब आप अपने बच्चे को तुरंत चालू करते हैं तो माता-पिता के कन्स्ट्रक्टर को फिर से बुलाया जाएगा। इसलिए सरोगेट का उद्देश्य डुप्लिकेट कन्स्ट्रक्टर का आह्वान करना है। –

संबंधित मुद्दे