2012-09-17 36 views
1

有没有什么办法可以将this传递到立即调用的函数表达式中,而不需要解析为var that = this(这在某些情况下不适用)?将THIS传递到立即调用的函数表达式

试过以下,但没有运气:

(function(that) { 
    console.log(that); 
})(this) 
+0

这是什么情况?你在对象上还是在函数上下文中调用该函数? .. function.apply(上下文,参数)形式可能是你正在寻找.. –

回答

5

您可能能够使用callapply用于这一目的。例如:

(function() { 
    console.log(this); // whatever that was specified in the "call" method 
}).call(this); 
0
(function(that) { 
    console.log(that); 
})(this); 

的代码应该工作,确保没有收到任何代码没有分号。

(function(that) { 
     console.log(that); 
})(this) // if here is no semicolon, the next code will be syntax error. 
(function(that) { 
     console.log(that); 
})(this); 

你可以试试下面的代码,即使它之前的代码省略了分号,也可以。

!function(that) { 
    console.log(that); 
}(this); 
相关问题