2013-04-04 62 views
2

呦,爲什麼使用Javascript對象,而不是原型

我的問題是關於JavaScript對象。

我讀過Backbone.js的代碼,我看到模型和對象是使用JavaScript對象定義對象。

就像那個

Backbone.Model.extend({ 
    initialize: function() { ... }, 
    author: function() { ... }, 
    coordinates: function() { ... }, 
    allowedToEdit: function(account) { 
     return true; 
    } 
}); 
爲什麼不使用原型

? 因爲它是爲每個班級重新定義的方法? 因爲創建的每個對象比backboneJS佔用更多空間?

如果有人可以解釋給我聽的時候,爲什麼它們也同樣吸引使用原型?

+0

笑爲「喲」 – Ezeewei 2015-04-30 20:57:23

回答

2

您用於在Backbone中創建對象的擴展方法USE原型,您只是看不到它。
至於另外一個問題,我想你的答案是正確的,就像你問你的第一個問題:)。另外,從some benchmarks I saw開始,如果實例化許多對象,則使用原型會更快。也就是說,如果你使用單例,你可能想使用靜態屬性(extend(protoProp,staticProp))。

相關骨幹的代碼(擴展函數的定義):

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); 
+0

好了,我反把它...原型這麼想的重複方法。你有基準的例子嗎?僅供參考。感謝的 – 2013-04-04 08:02:28

+0

@SimonPaitrault [在這裏你去(http://stackoverflow.com/questions/3493252/),我設法找到它:)總體一個非常有趣的帖子JavaScript開發者。 – Loamhoof 2013-04-04 08:11:32

+0

感謝您的鏈接。 JavaScript原型中的靜態變量是什麼? – 2013-04-04 08:43:38

1

你似乎誤解。這裏的源代碼:

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(){ return 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; 
}; 

這可能是混亂的,但這裏的本質是骨幹.extend方法,創造了新的功能,傳遞對象分配給它的原型,並將其返回。

至於第二個問題:總是用原型,如果你正在處理的對象共享相同的功能的倍數。

0

這裏要擴展一個模型,這是很好的使用JS對象。但是,如果你想實現一個OOP類,接口或庫去JS原型。

相關問題