Difference between IIFE and call

时光总嘲笑我的痴心妄想 提交于 2019-12-21 09:30:08

问题


Is there a difference between:

(function(){

}).call(this);

and

(function(){

})();

or

var MODULE = {};
(function(){
    this.hello = 'world'
}).call(MODULE);

and

var MODULE = {};
(function(m){
    m.hello = 'world'
})(MODULE);

I often see the first case in compiled javascript. They both would create a scope and do their namespacing job well.

Is there any difference or is it just a matter of taste.

Edit: And why would compiled javascript would use call over IIFE?


回答1:


(function(){

}).call(this);

calls the anonymous function where the this inside the function will point to the object referred by this when the call was made.

(function(){

})();

calls the anonymous function where the this inside the function will point to the global object (or undefined in strict mode)

Demo: Fiddle



来源:https://stackoverflow.com/questions/17606691/difference-between-iife-and-call

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