javascript模块模式中未定义变量的重点是什么?

时间:2014-09-12 06:07:54

标签: design-patterns javascript commonjs

我遇到了以下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);  

2 个答案:

答案 0 :(得分:2)

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

undefined = true;

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

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

答案 1 :(得分:1)

在某些浏览器中可以覆盖

undefined。这可以通过将undefined重新定义为不存在的参数的值来解决范围中的问题。