通过这个入立即调用的函数表达式(Passing THIS into an Immediately-I

2019-09-27 01:55发布

有没有办法通过this入立即调用的函数表达式,而不解决以var that = this (这并不适用于某些情况下)?

试过以下,但没有运气:

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

Answer 1:

你也许可以使用callapply用于此目的。 例如:

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


Answer 2:

(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);


文章来源: Passing THIS into an Immediately-Invoked Function Expression