将其传递给立即调用的函数表达式

时间:2012-09-17 09:49:53

标签: javascript this

有没有办法将this传递给立即调用的函数表达式,而不解析为var that = this(在某些情况下不适用)?

尝试以下但没有运气:

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

2 个答案:

答案 0 :(得分:5)

您可以将callapply用于此目的。例如:

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

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