我想知道如何更改jQuery回调函数的上下文,以使this与父函数中的相同。

请看以下示例:

var context = this;
console.log(context);

element.animate(css, speed, type, function () {
     var new_context = this;
     console.log(new_context);
});


如何使new_context等于context

我意识到我可以做到这一点:

var new_context = context;


但是,有没有更好的办法告诉函数使用不同的上下文呢?

最佳答案

您可以使用闭包:

var context = this;
console.log(context);

element.animate(css, speed, type, function () {
     var new_context = context; // Closure
     console.log(new_context);
});


您也可以这样做:

// First parameter of call/apply is context
element.animate.apply(this, [css, speed, type, function () {
     var new_context = this;
     console.log(new_context);
}]);

09-25 18:16
查看更多