Javascript Module Pattern Uncaught Reference Error -


i've been following this tutoral, , when referencing module argument in moduletwo, works fine until comment out module.

my understanding double pipes || , empty object {} create empty object in place of module if it's undefined, instead i'm getting error in console.

var module = (function () {    var privatemethod = function () {     // private   };    var somemethod = function () {     // public   };    var anothermethod = function () {     // public   };    return {     somemethod: somemethod,     anothermethod: anothermethod   };  })();  var moduletwo = (function (module) {      module.extension = function () {         // method!     };      return module;  })(module || {}); 

basically, there’s error in tutorial. 1 way make things work suggested rplantiko, might easier write window.module || {} instead of module || {}.

how things work here:

  • accessing non-existent property of object yields undefined. however, referencing variable hasn’t been declared yields referenceerror (so understanding little bit off there).
  • browser puts global variables properties onto global window object. module in tutorial global variable, because it’s declared outside functions, can access via window.module, not cause referenceerror if undefined (per previous point).

it might practice explicitly assign window global variable define (e.g., window.module = (function () { … if intend make module global), that’s arguable , out of scope of discussion.


Comments

Popular posts from this blog

yii2 - Yii 2 Running a Cron in the basic template -

asp.net - 'System.Web.HttpContext' does not contain a definition for 'GetOwinContext' Mystery -

mercurial graft feature, can it copy? -