javascript中的OO编程:将属性作为对象本身是一种好习惯吗?

L. *_*nna 2 javascript oop backbone.js

我用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);
            }
        }
    }
});
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,对象Map的属性引导是一个Collection Leads,当它被创建时.但是,这不像Java那样有效,因为我被迫使用:

this.attributes.leads
Run Code Online (Sandbox Code Playgroud)

称之为attribut线索的方法之一.

题:

将对象用作属性是不好的做法,如果是,我该怎么办?

Boj*_*les 5

你应该只能this.get('leads').add(lead)在你的循环中做; this.get('leads)在这种情况下,将返回(引用)leads具有该add()方法的集合.你做不到this.leads.add因为this.leads不存在.

Backbone this.attributes是获取模型的所有属性的便捷方式,但是当调用这些属性时触发事件时this.set(),this.get()它们更适合作为接口.