closures - Javascript Module Using Apply and Returning This -


i have been in constant search simple javascript module pattern. have read pretty every article can find. module patterns create object, add functions it, return object , expose public methods, this:

var module = (function() {     var exports = {}, x = 1;      function private() {         return x;     }      exports.public = function() {         return x;     };      return exports; }()); 

this seems on long term may pain, looking easier way. i've seen can call apply function, , pass in object, use "this" reference , return "this" same effect, this:

var module = (function() {     var x = 1;      function private() {         return x;     }      this.public = function() {         return x;     };      return this; }).apply({}); 

is there wrong using apply , passing in empty object? seems best way "this" keyword goes nicely js intellisense coloring, , seems easier understand. see problems or have simpler way?

this seems best way "this" keyword goes nicely js intellisense coloring

that shouldn't argument :-)

seems easier understand.

not me, actually. this typically used in constructors , in object methods only, not in iefes (unless refers same this outside of iefe, i.e. global object). understand doing here, i'd have scroll down end of file find out how function called.

anybody see problems this

yes. apart being unusual, deprives of static, local reference module object. if want call 1 of public methods somewhere in module, can use this (inside other public methods) or module, neither of them works same exports.

or have simpler way?

you mix 2 patterns:

var module = (function(exports) {     var x = 1;      function private() {         return x;     }      exports.public = function() {         return x;     };      return exports; }({})); 

Comments

Popular posts from this blog

android - MPAndroidChart - How to add Annotations or images to the chart -

javascript - Add class to another page attribute using URL id - Jquery -

firefox - Where is 'webgl.osmesalib' parameter? -