2013-04-04 64 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原型。

相关问题