jQuery更改回调上下文

时间:2013-01-08 10:01:26

标签: javascript jquery

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

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

1 个答案:

答案 0 :(得分: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);
}]);