Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing parameter to a module javascript

I am using module pattern in javascript. Is it a way to create instances of a "class" ? I am using it in a right way ?

var moduleClass = (function () {
var a =5;
return {
getA: function () {
  console.log(a);
 }
};
})();
var instance = moduleClass;
instance.getA();

http://jsfiddle.net/PzLKy/ How can I pass parameters on new instances ?

like image 495
Petran Avatar asked Jul 18 '13 19:07

Petran


1 Answers

You don't really need new here, Below is the right way to code to achieve what you are trying to achieve. Also, be really careful while using new, if used unwisely it can start clobbering your Global variable, If you want to use new, John Resig has a really nice explaination for how to do it the right way, for more read this article by John Resig http://ejohn.org/blog/simple-class-instantiation/

http://jsfiddle.net/PzLKy/2/

var moduleClass = (function () {
    var a =5;

  return {
      setA: function (inA) {
      a=inA;
    } ,
    getA: function () {
      alert(a);
    }

  };

})();


var instance = moduleClass;
instance.setA(8);
instance.getA();

Edit: contactmatt is right, definitely dont be afraid of using constructor, but here is some thing you need to be aware of

Taken from John Resig's article mentioned in the first paragraph,

suppose this is your code

function User(first, last){
    this.name = first + " " + last;
}

var user = new User("John", "Resig"); 
user.name // John Resig
var user2 = User ("first","last");
user2.name //undefined, also this would pollute your current scope

if you call the constructor, you would not get any kind of indication and can be a debugging nightmare.

a way to solve this is

function User(first, last){
  if ( this instanceof User ) {
    this.name = first + " " + last;
  } else
    return new User(first, last);
}

To Conclude,

So if you feel that constructor is the best way for your problem, use it. But be aware, also the simple class instantiation by John is a really useful pattern, try to go through it,he also explains generic constructor.

like image 150
user2580076 Avatar answered Sep 24 '22 17:09

user2580076