javascript模块模式中未定义变量的意义何在

What is the point of undefined variable in javascript module pattern

本文关键字:变量 模块 模式 未定义 javascript      更新时间:2023-09-26

我遇到了下面的javascript模块模式,并且非常喜欢它,但是,为什么在参数中使用undefined

(function(window, document, undefined){
    'use strict';
    var MyWidget = function(){
        if (!(this instanceof MyWidget)) {
            var test = new MyWidget();
            return test.init.call(test, Array.prototype.slice.call(arguments));
        }
      var firstPrivateVar = 'aa',
          secondPrivateVar = 'bb';
      this.init = function(options){
        console.log('MyWidget.init', options);
        return true;
      };
      this.setStuff = function(){
      };
    };
    window.MyWidget = MyWidget;
})(window, document);  

在ECMAScript 3中,开发人员有权使用未定义的关键字作为变量,即它是可变的。所以如果我要写

undefined = true;

undefined的值将为true,它将失去其真正的含义。在上面提到的场景中,我们传递的是窗口对象、文档对象,并且没有第三个参数。这意味着在function(window, document, undefined)中,未定义的变量实际上是未定义的,因为我们没有向它传递任何参数

根据ECMAScript5,这个未定义的不再可变

undefined在某些浏览器中可以被覆盖。这通过将undefined重新定义为不存在的参数的值来修复作用域中的问题。