【问题标题】:Is passing the window object to an IIFE optional? [duplicate]将窗口对象传递给 IIFE 是可选的吗? [复制]
【发布时间】:2017-12-16 11:38:13
【问题描述】:

下面的例子有什么区别吗?

示例 1:

(function (window) {
 'use strict';
  console.log(window)
})(window);

示例 2:

(function () {
 'use strict';
  console.log(window)
})();

传递窗口对象是可选的吗?

【问题讨论】:

    标签: javascript


    【解决方案1】:

    #1 没什么意义。 window 是只读的,不能重新定义,所以不需要像 #1 那样在某个时间点捕获它的值。 #2 很好。

    #1 使用的模式主要用于捕获稍后可能被其他代码更改的内容,例如:

    var x = 1;
    (function(x) {
        setTimeout(function() {
            console.log("inside, x = " + x);
        }, 100);
    })(x);
    x = 2;
    console.log("outside, x = " + x);

    ...或为事物获得方便的简写名称:

    (function(d) {
        var div = d.createElement("div");
        div.innerHTML = "Hi";
        d.body.appendChild(div);
    })(document);

    它也常用于获取undefined,以防undefined标识符被修改:

    (function(u) {
        console.log(typeof u); // "undefined"
    })(/*Note there's no argument passed*/);

    现在undefined 是只读的并且不能重新定义,因此不再需要这样做。

    【讨论】:

      猜你喜欢
      • 2013-06-07
      • 2014-04-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-09
      • 2015-06-28
      • 1970-01-01
      相关资源
      最近更新 更多