I some times create class like this
function class1(){
.....
class1.prototype.callme = function(){
alert("hai");
}
}
then I instantiate using (new class1()).callme();
and some times I use modular pattern
var class2 = (function(){
var privatemethod = function(){
....
}
var publicmethod = function(){
alert("am public");
}
return{
callme:publicmethod
}
})();
then I call class2.callme()
Whats the advantage and disadvantage, can some body please explain.
The first one is a constructor the second one is an object, so they're not the same. You might want to use one or other in different situations. In any case you usually declare the prototype outside the constructor and use this.property for public methods and variables. The second option is not reusable as a class, unless you use something like jQuery's extend or Underscore's _extend, which is the way I usually do it, it seems simpler without the prototype chain bloated code.
If you want to learn about the different Javascript patterns I would definitely recommend Learning JavaScript Design Patterns Its free/opensource and kept constantly updated.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With