javascript将变量传递给函数内的函数

Mr *_*bri 0 javascript jquery

我在使用以下内容显示'name'的值时遇到问题:

   for (var name in array) {
        var hoverIn = function() {
                  alert(name);
        };

        var hoverOut = function() {
        };

        thing.hover(hoverIn, hoverOut);

   }
Run Code Online (Sandbox Code Playgroud)

我得到的是一个警告窗口,其中包含姓名的最后一个值.显然,我做错了,我怀疑这是一个简单的修复.有人可以帮忙吗?

谢谢.

And*_*ong 7

这是闭包问题,name在迭代是最后一次name之后array,并且当迭代发生时不会立即执行悬停的回调,因此当实际执行悬停功能时,name将始终是最后一次array.

您需要使用IEFE(立即执行的函数表达式):

   for (var name in array) {
        // pass in name to the anonymous function, and immediately
        // executes it to retain name when the particular iteration happens
        var hoverIn = (function(name) {
             return function() {
                  alert(name);
             }
        })(name); // if you notice, the pattern is (function(name) {})(name) 
                  // the first () creates an anonymous function, the (name) 
                  // executes it, effectively passing name to the anon fn

        var hoverOut = (function(name) {
            // same pattern if you need to re-use name inside here, otherwise just
            // function() { } should suffice
        })(name);

        thing.hover(hoverIn, hoverOut);

   }
Run Code Online (Sandbox Code Playgroud)

为了避免重复(function() { })()(真正令人厌倦看),你也可以像@pimvdb所指出的那样,将整个身体包裹在一个闭包中:

   for (var name in array) {
        (function(name) {
           var hoverIn = function() {
               alert(name);
           }

           var hoverOut = function() {
           }

           thing.hover(hoverIn, hoverOut);
        })(name); // closure of for loop body

   }
Run Code Online (Sandbox Code Playgroud)