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;
};