Passing THIS into an Immediately-Invoked Function Expression

六眼飞鱼酱① 提交于 2019-12-13 18:56: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)

回答1:


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



回答2:


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


来源:https://stackoverflow.com/questions/12456830/passing-this-into-an-immediately-invoked-function-expression

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!