1

我想知道如何更改 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;

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

4

1 回答 1

1

您可以利用闭包:

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);
}]);
于 2013-01-08T10:02:58.423 回答