what is the best way to create classes ( as in OOP) in Javascript ? Right now I am using the following pattern . Is it ok ?
var myclass = (function() {
var _name;
var baseObject = {
a: 10,
c: function() {
return _name + " world " + privateFunc();
}
};
function privateFunc() { return _name + "-ba"; };
function myclass(name) {
_name = name;
this.x = 9;
};
myclass.prototype = baseObject;
return myclass; })();
what is the best way to create classes ( as in OOP) in Javascript ? Right now I am using the following pattern . Is it ok ?
var myclass = (function() {
var _name;
var baseObject = {
a: 10,
c: function() {
return _name + " world " + privateFunc();
}
};
function privateFunc() { return _name + "-ba"; };
function myclass(name) {
_name = name;
this.x = 9;
};
myclass.prototype = baseObject;
return myclass; })();
Share
Improve this question
edited Dec 27, 2012 at 6:01
Mohammed H
7,04819 gold badges82 silver badges128 bronze badges
asked Mar 22, 2011 at 8:22
user670800user670800
1,1151 gold badge11 silver badges16 bronze badges
1
- That looks quite similar to the way coffeescript compiled class output looks like – david Commented Mar 22, 2011 at 8:45
4 Answers
Reset to default 8In 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());
There is no "best" way. There are a few OOP patterns in JavaScript, and the one you mentioned is one of them (and also a popular one). It is essentially a prototypical (or pseudo-classical) pattern with a closure to encapsulate private class-based static variables.
There are other patterns (e.g. the functional pattern recommended by Douglas Crockford).
I personally recommend the pseudo-classical pattern (although which pattern is best is a hot area of debate).
If you are doing OOP with JavaScript, I strongly recommend that you look into adopting a JavaScript library that has OOP built in, such as The Dojo Toolkit or the Closure Library. Other libraries (e.g. jQuery, MOOtools, Ext etc.) all have OOP modules and/or plugins.
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