Mutable variable is accessible from closure. How can I fix this?

前端 未结 5 1911
没有蜡笔的小新
没有蜡笔的小新 2020-12-12 12:17

I am using Typeahead by twitter. I am running into this warning from Intellij. This is causing the \"window.location.href\" for each link to be the last item in my list of i

5条回答
  •  执笔经年
    2020-12-12 12:37

    You need to nest two functions here, creating a new closure that captures the value of the variable (instead of the variable itself) at the moment the closure is created. You can do this using arguments to an immediately-invoked outer function. Replace this expression:

    function (item) { // what to do when item is selected
        comp = me.map[item];
        if (typeof comp === 'undefined') {
            return this.query;
        }
    
        window.location.href = me.format(gotoUrl, comp.s, target.destination);
    
        return item;
    }
    

    With this:

    (function (inner_target) {
        return function (item) { // what to do when item is selected
            comp = me.map[item];
            if (typeof comp === 'undefined') {
                return this.query;
            }
    
            window.location.href = me.format(gotoUrl, comp.s, inner_target.destination);
    
            return item;
        }
    }(target))
    

    Note that we pass target into the outer function, which becomes the argument inner_target, effectively capturing the value of target at the moment the outer function is called. The outer function returns an inner function, which uses inner_target instead of target, and inner_target will not change.

    (Note that you can rename inner_target to target and you will be okay -- the closest target will be used, which would be the function parameter. However, having two variables with the same name in such a tight scope could be very confusing and so I have named them differently in my example so that you can see what's going on.)

提交回复
热议问题