2012-12-20 24 views
8

Sử dụng Backbone.js, giao diện điều khiển của tôi đã ghi lại phiên bản Backbone.View.extend({}) để tìm loại __proto__ để thay thế.__proto__ Loại thay thế bằng JavaScript là gì?

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

Điều này dẫn đến một đối tượng với kiểu Surrogate cho nó __proto__

__proto__: Surrogate 

Surrogate là gì?

Trả lời

11

Surrogate là một lớp "helper" trong Backbone để thiết lập chuỗi nguyên mẫu. Kiểm tra mã nguồn:

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

Cảm ơn bạn đã trả lời. Bạn/ai đó biết: Điều gì có thể là lý do/lý do cho điều ước "để tránh gọi nhà xây dựng của cha mẹ ở đây?" – humanityANDpeace

+1

@humanityANDpeace, không có hàm tạo của Surrogate sẽ khởi tạo khi nhân bản parent.prototype -> child.prototype = new parent(); thì hàm tạo của cha mẹ sẽ được gọi lại khi bạn khởi tạo con bạn. vì vậy mục đích của Surrogate là tránh constructor gọi lặp lại. –