2012-12-20 9 views
8

Backbone.jsを使用して、私はBackbone.View.extend({})のインスタンスをログに記録して、__proto__タイプをサロゲートにしました。JavaScriptで__proto__ type surrogateとは何ですか?

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

@humanityANDpeace、代理人のコンストラクタなしでは、parent.prototype - > child.prototype = new parent();の複製時に開始されます。 あなたの子供をインスタンス化すると、親のコンストラクタが再び呼び出されます。 Surrogateの目的は、重複したコンストラクターの呼び出しを避けることです。 –

関連する問題