我已经使用 Backbone 创建了一些对象,就像我在 Java 中所做的那样。
var Lead = Backbone.Model.extend({
defaults: {
lng: 0,
lat: 0,
distance: 0
},
initialize: function () {
}
});
var Leads = Backbone.Collection.extend({
model: Lead
});
var Map = Backbone.Model.extend({
defaults: {
leads: null
},
initialize: function () {
this.set("leads",new Leads());
},
addJson: function (json) {
var key;
for (key in json) {
if (json.hasOwnProperty(key)) {
var lead = new Lead({ lng: parseFloat(json[key].lng.replace(",", ".")), lat: parseFloat(json[key].lat.replace(",", ".")), distance: json[key].distance });
this.attributes.leads.add(lead);
}
}
}
});
如您所见,对象Map的属性leads在创建时是一个Collection Leads。然而,这在 Java 中效果并不好,因为我被迫使用:
this.attributes.leads
调用属性线索的方法之一。
问题:
使用对象作为属性是不好的做法吗?如果是,我该怎么办?
最佳答案
您应该能够在循环中执行 this.get('leads').add(lead)
;在这种情况下,this.get('leads)
将返回(引用)具有 add()
方法的 leads
集合。您无法执行 this.leads.add
,因为 this.leads
不存在。
Backbone 的 this.attributes
是获取模型所有属性的便捷方法,但是 this.set()
和 this.get()
是首选接口(interface),因为调用这些接口(interface)时会触发事件。
关于javascript - javascript 中的面向对象编程 : is it good practice to have attributes being objects themselves?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16794050/