samedi 14 mars 2015

How avoid getter/setter functions in the module pattern when passing arguments

For some time now, I've been structuring my JavaScript Code like this:



;(function() {
function Example(name, purpose) {
this.name = name;
this. purpose = purpose;
}

Example.prototype.getInfo = function() {
return 'The purpose of "' + this.name + '" is: ' + this.purpose;
}

Example.prototype.showInfo = function() {
alert(this.getInfo());
}

var ex = new Example('someModule', 'Showing some stuff.');

ex.showInfo();
})(undefined);


Fiddle


Now I've realized that this pattern is far from ideal as is has some problems:



  • It doesn't utilize closures/scope so simulate public & private members.

  • It doesn't export something, meaning the module itself is not really encapsulated & namespaced.


(Disclaimer: I haven't used it in any bigger project, so I might be missing some important details that occur when working under real live conditions.)


To solve these issues, I started looking into JavaScript design patterns. One of patterns that immediately appealed to me is the module pattern.

I tried to rewrite the code above using the module pattern, but I can't get it quite right:



var Example = (function() {

function getInfo() {
return 'The purpose of "' + name + '" is: ';
}

// Public stuff
return {
name: '',
purpose: '',
setInfo: function(name, purpose) {
this.name = name;
this.purpose = purpose;
},
showInfo: function() {
alert(getInfo());
}
};
})(undefined);

Example.setInfo('someModule', 'Showing some stuff.');
Example.showInfo();


Non working Example: Fiddle


Now the module itself is encapsulated inside the Example namespace & there is something like public & private members, but working with it is quite different & difficult to me, probably because I can't wrap my head around the fact that there is no instance created using the new keyword.


In the non working example, why does it alert result although that string is never set & why is purpose not alerted? I think the setInfo method itself works, so it's probably a scope issue I don't understand.


Also, is there a way around using getter/setter functions? To me it currently looks like assignments I would normally do in the constructor aren't really possible using the module pattern:



function Example(name, purpose) {
this.name = name;
this. purpose = purpose;
}


Using the module pattern, I either have to user getter/setter or something like a 'universal setter function' in form of an init function.


Coming from PHP OOP, I always try to avoid them as much as possible, but I don't really know how to handle that in a prototype based language.


Maybe there is something similar to the module pattern, but with using prototypes – something like module & constructor pattern? It might be easier for me to understand.


Aucun commentaire:

Enregistrer un commentaire