what pattern to use when creating javascript class?
In my opinion, the best way to create classes in JavaScript is "don't". Forgive me for being blunt, but when working with JavaScript, try to forget about classes – they don't exists here – and accept that the language only deals with objects.
Not having classes in the language, means less code to be written. In typical applications, most objects don't have any siblings. You will only ever have one document
, one window
, one userList
, etc. Create these objects by using object literal notation:
var userList = {
users: []
};
While there are no classes in JavaScript, there are constructors and prototypes. These concepts come in handy when you have several objects that are similar (eg users contained in a userlist
). Your code sample uses both of these concepts. Using names like myclass
, it is hard to tell what you are trying to model. Here's an example of a User
constructor and an extention to it's prototype:
var User = function (name) {
this.name = name;
};
User.prototype.sayHello = function () {
return "Hello, my name is " + this.name;
};
The following example illustrates a pattern that I personally developed over time.
It exploits scoping to allow private fields and methods.
Employee = (function(){
// private static field
var staticVar;
// class function a.k.a. constructor
function cls()
{
// private instance field
var name = "";
var self = this;
// public instance field
this.age = 10;
// private instance method
function increment()
{
// must use self instead of this
self.age ++;
}
// public instance method
this.getName = function(){
return cls.capitalize(name);
};
this.setName = function(name2){
name = name2;
};
this.increment = function(){
increment();
};
this.getAge = function(){
return this.age;
};
}
// public static field
cls.staticVar = 0;
// public static method
cls.capitalize = function(name){
return name.substring(0, 1).toUpperCase() +
name.substring(1).toLowerCase();
};
// private static method
function createWithName(name)
{
var obj = new cls();
obj.setName(cls.capitalize(name));
return obj;
}
return cls;
})();
john = new Employee();
john.setName("john");
mary = new Employee();
mary.setName("mary");
mary.increment();
alert("John's name: " + john.getName() + ", age==10: "+john.getAge());
alert("Mary's name: " + mary.getName() + ", age==11: "+mary.getAge());
Javascript uses prototypical inheritance.
If you want to create custom classes I would recommend reading up what prototypical inheritance is about instead of trying to force c# methodology onto js (implementing class based inheritance over prototypical)
http://phrogz.net/js/classes/OOPinJS.html