在Javascript中按值传递变量

时间:2016-07-22 17:51:39

标签: javascript loops reference

我已经看到了很多类似的问题,但我觉得我仍然缺少某些东西。我有以下代码:

_setHotKeys: function(values, buttons){
    var hotKeyMap = {
            target: document, 
            binding:[]
        }; 

        values.forEach(function(value, index){
            if(value.hotkey){
                this.button = buttons[index]; 
                hotKeyMap.binding.push({
                    key: value.hotkey,
                    fn: function(key, event){
                        this._handleFillInValueButtonToggle(this.button, true); 
                    },
                    scope: this 

                }); 
            }

        }, this)    


        var keyMap = new Ext.util.KeyMap(hotKeyMap); 
},

在这个函数中,我试图使用Ext.js设置热键。此代码将为value数组中的每个值设置一个热键,但它们都将this.button设置为buttons数组中的最后一个按钮。我的结论是它将this.button的引用推送到数组中而不是值,因此随着循环的进行,此值会发生变化。如何将其设置为推送值而不是引用?

1 个答案:

答案 0 :(得分:4)

你的结论是正确的。

对于循环的每次迭代,您已将this.button指定为等于循环索引处的按钮。如果我们打破这个,看起来像;

this.button = buttons[0]
this.button = buttons[1]
this.button = buttons[2]

依此类推,直到它到达循环结束。一旦到达循环结束this.button等于数组中的最后一个按钮。因此,当热键事件执行时,它会自然地使用对this.button的引用,该引用指向数组中的最后一个按钮。

您应该直接将按钮[index]引用传递给您的处理程序,而不是将引用分配给类属性。

...
fn: function(key, event) {
   this._handleFillInValueButtonToggle(button[index], true);
}