Javascript MVC和语法问题

时间:2011-04-13 09:17:47

标签: javascript model-view-controller javascript-events javascript-framework

我看到了一篇javascript MVC文章here,该模型被定义为:

var ListModel = function (items) {
    this._items = items;
    this._selectedIndex = -1;

    this.itemAdded = new Event(this);
    this.itemRemoved = new Event(this);
    this.selectedIndexChanged = new Event(this);
};

ListModel.prototype = {

    getItems : function () {
        return [].concat(this._items);
    },

    addItem : function (item) {
        this._items.push(item);
        this.itemAdded.notify({item: item});
    },

    removeItemAt : function (index) {
        var item = this._items[index];
        this._items.splice(index, 1);
        this.itemRemoved.notify({item: item});
        if (index == this._selectedIndex)
            this.setSelectedIndex(-1);
    },

    getSelectedIndex : function () {
        return this._selectedIndex;
    },

    setSelectedIndex : function (index) {
        var previousIndex = this._selectedIndex;
        this._selectedIndex = index;
        this.selectedIndexChanged.notify({previous: previousIndex});
    }

};  

问题1 。在javascript中,下划线意味着什么?例如this._items

问题2 。在模型中,它在哪里使用,如何使用以下内容:

this.itemAdded = new Event(this);
    this.itemRemoved = new Event(this);
    this.selectedIndexChanged = new Event(this);

2 个答案:

答案 0 :(得分:7)

下划线只是惯例,它只是意味着在他们写作时指示某些人的头部。通常人们使用下划线来为方法名称添加前缀,这些方法名称是私有方法,这意味着仅在内部使用类,而不是其他用户使用。

答案 1 :(得分:1)

下划线并不意味着什么,您可以在变量名中使用它。

在这种情况下,它似乎表明它应该用于私有变量。