javascript - Module pattern & "private attributes" -


ok, couple of weeks ago, learned "module pattern" in javascript. examples found went :

var module = (function () {     // private variables , functions     var foo = 'bar';      // constructor       var module = function () {     };      // public methods     module.prototype = {         something: function () {         }     };      // return module     return module; })();  var my_module = new module(); 

i excited, started own test :

var mymodule = mymodule || {};  mymodule.user = (function(){     "use strict";      // "private" attribut     var id      //constructor     var user = function(l_id){         id = l_id;     };      //"public" method     user.prototype.getid = function(){ return id };       return user; })();  var u2 = new mymodule.user(2); var u1 = new mymodule.user(1); console.log(u2.getid()); // print 2 console.log(u1.getid()); //print 2 oo 

however, didn't expect called "private" attribut "id", not instance variable. , if had paid attention, have noticed scope of such variable... terribly misunderstood "private variables , functions" comment...

nevertheless, determined found way used private instance variable within module.

for moment solution found old way :

mymodule.user = (function(){     "use strict";      //constructor     var user = function(id){                 this.getid = function(){ return id; };     };         return user; })(); 

but there no prototype avantages anymore...

do have better way mixe "module pattern" , use of private instance variables ?

well frankly speaking i've never used module pattern constructor, feel there better ways, achieve you're looking (that if understood correct) can this:

var prefixmodule = (function () {     // going static ... that's real title !     var statictitle = "intergalactic federation king almighty , commander of universe";      var prefixmodule = function () {         // instance variable         this.secretprefix = statictitle + " ::";     };      // hidden world     var generaterandomnumber = function() {         return math.floor(math.random() * 100);     };      prefixmodule.prototype.prefixname = function (name) {         var randomnumber = generaterandomnumber();         return this.secretprefix + " " + name + " | " + randomnumber;     };      return prefixmodule; })();  var m1 = new prefixmodule(); var m2 = new prefixmodule(); var m3 = new prefixmodule();  console.log(m1.prefixname("jon skeet")); console.log(m2.prefixname("chuck norris")); console.log(m3.prefixname("vbarthel-fr")); 

here fiddle.

also, should clarify in case id set static variable , it's shared between modules. hope helps.


Comments

Popular posts from this blog

linux - xterm copying to CLIPBOARD using copy-selection causes automatic updating of CLIPBOARD upon mouse selection -

c++ - qgraphicsview horizontal scrolling always has a vertical delta -