Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript coding difference

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.

like image 899
Navin Leon Avatar asked Feb 18 '26 04:02

Navin Leon


2 Answers

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.

like image 154
elclanrs Avatar answered Feb 20 '26 16:02

elclanrs


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.

like image 39
Jason Kulatunga Avatar answered Feb 20 '26 16:02

Jason Kulatunga



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!