当对集合和模型使用扩展时,不是主干方法的属性是否设置为定义的“类”的原型(prototype)值?这意味着如果在类的一个实例中修改了这些属性,那么类的所有实例都会更改这些属性?
我遇到了类似于以下问题的问题。
例如:
var MyCollection = Backbone.Collection.extend({
options:
{
someAttribute: null,
anotherAttribute : null
},
url : function()
{
return this.options.someAttribute + "/" + this.options.anotherAttribute
});
var myCollectionInstance1 = new MyCollection();
_.extend(myCollectionInstance1.options,{
someAttribute: "page1",
anotherAttribute : "location1"});
var myCollectionInstance2 = new MyCollection();
_.extend(myCollectionInstance2.options,{
someAttribute: "page1",
anotherAttribute : "location2"});
// I call fetch here which will eventually run into my redefined url
// and now my url for this function is going to be
// "page1/location2" instead of what I expect "page1/location1"
// I assume this is because the protoype is being changed in the above
// of myCollectionInstance2.options
myCollectionInstance1.fetch();
如果是这种情况,那么将实例变量附加到集合的最佳方法是什么?
最佳答案
是的,extend
的第一个参数中的所有内容都在原型(prototype)中结束,因此由实例共享。可变属性(例如对象和数组)的常见解决方案是在 initialize
中分配它们:
var MyCollection = Backbone.Collection.extend({
initialize: function(options) {
this.options = {
someAttribute: null,
anotherAttribute: null
};
// The rest of the initialization goes here...
}
});
如果您想将它们保留在原处以供文档使用,那么您可以 _.clone
在初始化
中:
var MyCollection = Backbone.Collection.extend({
default_options: {
someAttribute: null,
anotherAttribute: null
},
initialize: function(options) {
this.options = _(this.default_options).clone();
// The rest of the initialization goes here...
}
});
请注意,_.clone
仅进行浅拷贝,因此如果 this.options
包含嵌入式数组或对象,您仍可能以意外共享告终。
关于javascript - Backbone.*.extend 是否为定义的类设置原型(prototype)值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23575762/