如何在javascript中更改函数的上下文 [英] How to change the context of a function in javascript
问题描述
我试图理解为什么在javascript中,您可能想要更改函数的上下文。我正在寻找一个真实世界的例子,或者一些能够帮助我理解如何/为什么使用这种技术以及它的重要性的东西。
使用此示例说明该技术(来自 http://ejohn.org/apps/learn/#25 )
var object = {};
函数fn(){
return this;
}
assert(fn()== this,上下文是全局对象。);
assert(fn.call(object)== object,上下文更改为特定对象。);
jQuery可以很好地利用它: p>
$('a')。each(function(){
//this是一个元素 - 很有用的
});
实际的jQuery代码如下所示:
for(name in object){
if(callback.call(object [name],name,object [name])=== false){
打破;
如果它只是做了 callback (name,object [name])
,那么这个
不会被设置为你迭代器中的当前对象,你必须使用参数。基本上它只是让事情变得更简单。
I'm trying to understand why in javascript, you might want to change the context of a function. I'm looking for a real world example or something which will help me understand how / why this technique is used and what its significance is.
The technique is illustrated using this example (from http://ejohn.org/apps/learn/#25)
var object = {};
function fn(){
return this;
}
assert( fn() == this, "The context is the global object." );
assert( fn.call(object) == object, "The context is changed to a specific object." );
解决方案 jQuery makes use of it to good effect:
$('a').each(function() {
// "this" is an a element - very useful
});
The actual jQuery code looks like this:
for ( name in object ) {
if ( callback.call( object[ name ], name, object[ name ] ) === false ) {
break;
}
}
If it just did callback( name, object[ name ] )
then this
wouldn't be set to the current object in your iterator and you'd have to use the parameter instead. Basically it just makes things easier.
这篇关于如何在javascript中更改函数的上下文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!