Navin Leon
Navin Leon

Reputation: 1166

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.

Upvotes: 3

Views: 80

Answers (3)

cuongle
cuongle

Reputation: 75306

For using Module pattern:

The freedom to have private functions which can only be consumed by our module. As they aren't exposed to the rest of the page (only our exported API is), they're considered truly private.

Given that functions are declared normally and are named, it can be easier to show call stacks in a debugger when we're attempting to discover what function(s) threw an exception.

As T.J Crowder has pointed out in the past, it also enables us to return different functions depending on the environment. In the past, I've seen developers use this to perform UA testing in order to provide a code-path in their module specific to IE, but we can easily opt for feature detection these days to achieve a similar goal.

Upvotes: 1

Jason Kulatunga
Jason Kulatunga

Reputation: 5894

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.

Upvotes: 2

elclanrs
elclanrs

Reputation: 94101

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.

Upvotes: 2

Related Questions