1

I come across the following javascript module pattern and like it very much, but, why the use of undefined in the argument?

(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);  
Ryan
  • 10,041
  • 27
  • 91
  • 156

2 Answers2

2

In ECMAScript 3 the developer had the right to use the undefined keyword as a variable i.e. it was mutable. So if I were to write

undefined = true;

the value of undefined would be true and it would lose its true meaning. In this above mentioned scenario, we are passing the window object, the document object and there is no third parameter. so this means that in function(window, document, undefined), the undefined variable will be actually undefined as we are not passing any parameter to it.

According to ECMAScript5, this undefined in not mutable any more

1

undefined can be overwritten in some browsers. This fixes the problem in your scope by redefining undefined to the value of a non-existent parameter.

Rob M.
  • 35,491
  • 6
  • 51
  • 50