简体   繁体   English

jquery回调匿名函数关闭

[英]jquery callback anonymous function closure

I've declared the variable elem in both of the loops below; 我在下面的两个循环中声明了变量elem ; however, when the anonymous function in the first loop gets called (after the 400ms fadeOut effect is finished) the elem seems to refer to the value of elem which was assigned in the second loop. 但是,当第一个循环中的匿名函数被调用时(在400ms fadeOut效果完成之后), elem似乎引用了在第二个循环中分配的elem的值。 In other words, the code works correctly if you rename elem in the second loop to any other variable name. 换句话说,如果将第二个循环中的elem重命名为任何其他变量名,则代码可以正常工作。

Is there a way to make a closure around the anonymous function so that the value of elem is not changed in the context of the anonymous function? 有没有办法围绕匿名函数进行闭包,以便在匿名函数的上下文中不更改elem的值?

for (var i = 0; i < outs.length; i++) {
  var elem = this.elementAtPoint(outs[i]);

  $(elem).fadeOut(400, function () {
    $(elem).removeClass("white black queen"); //UPDATE
    $(elem).show();
  });
  //$(elem).css("background", "red");
}

for (var i = 0; i < ins.length; i++) {
  var elem = this.elementAtPoint(ins[i]);
  var piece = this.board.pieceAt(ins[i]);

  $(elem).hide();

  $(elem).addClass(this.classForPiece(piece));

  $(elem).fadeIn(400);
}

You could use a anonymous self executing function 您可以使用匿名自执行功能

for (var i = 0; i < outs.length; i++) {
    (function(elem){
        $(elem).fadeOut(400, function () {
            $(elem).removeClass("white black queen"); //UPDATE
            $(elem).show();
        });
        //$(elem).css("background", "red");
    })(this.elementAtPoint(outs[i]));
}

in javascript, variable scope is decided by function, so you can wrap the two for loops in two function. 在javascript中,变量作用域由函数决定,因此可以将两个for循环包装在两个函数中。 a wrapper function example: 包装函数示例:

(function(){
    //put you for loop here
})();

I would avoid creating lots of closures inside loops, they would be inefficient as they create copies of the current scope. 我会避免在循环中创建大量的闭包,因为它们创建了当前作用域的副本,效率很低。 Instead I'd simply create a couple of extra functions then call them inside your loops: 相反,我只需创建一些额外的函数,然后在循环中调用它们:

var fadeInPiece = function(elem, piece){
  $(elem).hide();
  $(elem).addClass(this.classForPiece(piece));
  $(elem).fadeIn(400);
}

var fadeOutElem = function(elem){
  $(elem).fadeOut(400, function () {
    $(elem).removeClass("white black queen"); //UPDATE
    $(elem).show();
  });
}

for (var i = 0; i < outs.length; i++)
  fadeOutElement(this.elementAtPoint(outs[i]));

for (var i = 0; i < ins.length; i++)
  fadeInPiece(this.elementAtPoint(ins[i]), this.board.pieceAt(ins[i]));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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