javascript中的立即执行函数表达式(IIFE)

来源:互联网 发布:软件项目验收方案 编辑:程序博客网 时间:2024/05/18 04:14

同样是立即执行函数,(function(){})()和(function(){}).call(this)的区别

在严格模式下:

(function(){  "use strict";  console.log(this === window);    // true}).call(this);(function(){  "use strict";  console.log(this === window);    // false})();

在非严格模式下是:

(function(){  console.log(this === window);    // true}).call(this);(function(){  console.log(this === window);    // true})();

1。在严格模式下函数调用的this并不会默认为全局对象,使用(function(){}).call(this),确保函数调用的this指向调用函数的this。
2。隔离上下文,避免变量冲突。

详解javascript的立即执行函数表达式(IIFE)
使用(function(){}).call(this)代码包裹的好处

原创粉丝点击