Passing THIS into an Immediately-Invoked Function

2019-08-05 05:17发布

Is there any way to pass this into an Immediately-Invoked Function Expression, without resolving to var that = this (which isn't applicable on some cases)?

Tried the following but with no luck:

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

2条回答
SAY GOODBYE
2楼-- · 2019-08-05 05:59

You might be able to use call or apply for this purpose. For example:

(function() {
    console.log(this); // whatever that was specified in the "call" method
}).call(this);
查看更多
太酷不给撩
3楼-- · 2019-08-05 06:01
(function(that) {
    console.log(that);
})(this);

The code should work, make sure there is no code before it without a semicolon.

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

You could try the code below, which will be ok even the code before it omit the semicolon.

!function(that) {
    console.log(that);
}(this);
查看更多
登录 后发表回答