简体   繁体   中英

Passing a variable by value in Javascript

I've seen lots of similar questions, but feel like I'm still missing something. I have the following code:

_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); 
},

In this function I am trying to set up hotkeys using Ext.js. This code will set up a hotkey for each of the values in the value array, but they all set this.button to the last button in the buttons array. My conclusion is that it is pushing a reference to this.button rather than the value into the array, so as the loop progresses, this value changes. How can I set it to push the value instead of the reference?

You are on the right track with that conclusion.

For every iteration of the loop, you've assigned this.button to be equal to the button at that index of the loop. If we break this out, it looks like;

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

And so on until it reaches the end of the loop. Once it reaches the end of the loop this.button is equal to the last button in your array. So naturally when the hotkey event executes, it uses the reference to this.button , which points to the last button in your array.

Instead of assigning the reference to the class property, you should pass the button[index] reference to your handler directly.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM