2013-01-08 31 views
1

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

看看下面的例子:

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; 

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

+0

你为什么不使用上下文来指代父上下文? – Adil

+0

@Adil没有真正的理由我只是想知道我是否错过了一个技巧,并可以节省创造一些变数。 –

+0

hm var new_context = context? 但我宁愿使用上下文本身。 –

回答

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); 
}]); 
+0

所以这就是关闭......我从来没有正确理解它是什么。 –

+0

我没有投票给你。 –