3 ways to define a JavaScript class
Introduction
JavaScript is a very flexible object-oriented language when it comes to syntax. In this article you can find three ways of defining and instantiating an object. Even if you have already picked your favorite way of doing it, it helps to know some alternatives in order to read other people's code.
It's important to note that there are no classes in JavaScript. Functions can be used to somewhat simulate classes, but in general JavaScript is a class-less language. Everything is an object. And when it comes to inheritance, objects inherit from objects, not classes from classes as in the "class"-ical languages.
1. Using a function
This is probably one of the most common ways. You define a normal JavaScript function and then create an object by using the new keyword. To define properties and methods for an object created using function(), you use the this keyword, as seen in the following example.
function Apple (type) { this.type = type; this.color = "red"; this.getInfo = getAppleInfo; } // anti-pattern! keep reading... function getAppleInfo() { return this.color + ' ' + this.type + ' apple'; }
To instantiate an object using the Apple constructor function, set some properties and call methods you can do the following:
var apple = new Apple('macintosh'); apple.color = "reddish"; alert(apple.getInfo());
1.1. Methods defined internally
In the example above you see that the method getInfo() of the Apple "class" was defined in a separate function getAppleInfo(). While this works fine, it has one drawback – you may end up defining a lot of these functions and they are all in the "global namespece". This means you may have naming conflicts if you (or another library you are using) decide to create another function with the same name. The way to prevent pollution of the global namespace, you can define your methods within the constructor function, like this:
function Apple (type) { this.type = type; this.color = "red"; this.getInfo = function() { return this.color + ' ' + this.type + ' apple'; }; }
Using this syntax changes nothing in the way you instantiate the object and use its properties and methods.
1.2. Methods added to the prototype
A drawback of 1.1. is that the method getInfo() is recreated every time you create a new object. Sometimes that may be what you want, but it's rare. A more inexpensive way is to add getInfo() to the prototype of the constructor function.
function Apple (type) { this.type = type; this.color = "red"; } Apple.prototype.getInfo = function() { return this.color + ' ' + this.type + ' apple'; };
Again, you can use the new objects exactly the same way as in 1. and 1.1.
2. Using object literals
Literals are shorter way to define objects and arrays in JavaScript. To create an empty object using you can do:
var o = {};
instead of the "normal" way:
var o = new Object();
For arrays you can do:
var a = [];
instead of:
var a = new Array();
So you can skip the class-like stuff and create an instance (object) immediately. Here's the same functionality as described in the previous examples, but using object literal syntax this time:
var apple = { type: "macintosh", color: "red", getInfo: function () { return this.color + ' ' + this.type + ' apple'; } }
In this case you don't need to (and cannot) create an instance of the class, it already exists. So you simply start using this instance.
apple.color = "reddish"; alert(apple.getInfo());
Such an object is also sometimes called singleton. It "classical" languages such as Java, singleton means that you can have only one single instance of this class at any time, you cannot create more objects of the same class. In JavaScript (no classes, remember?) this concept makes no sense anymore since all objects are singletons to begin with.
3. Singleton using a function
Again with the singleton, eh?
The third way presented in this article is a combination of the other two you already saw. You can use a function to define a singleton object. Here's the syntax:
var apple = new function() { this.type = "macintosh"; this.color = "red"; this.getInfo = function () { return this.color + ' ' + this.type + ' apple'; }; }
So you see that this is very similar to 1.1. discussed above, but the way to use the object is exactly like in 2.
apple.color = "reddish"; alert(apple.getInfo());
new function(){...} does two things at the same time: define a function (an anonymous constructor function) and invoke it with new. It might look a bit confusing if you're not used to it and it's not too common, but hey, it's an option, when you really want a constructor function that you'll use only once and there's no sense of giving it a name.
Summary
You saw three (plus one) ways of creating objects in JavaScript. Remember that (despite the article's title) there's no such thing as a class in JavaScript. Looking forward to start coding using the new knowledge? Happy JavaScript-ing!
This entry was posted on Friday, September 29th, 2006 and is filed under JavaScript. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.
Get notification for future posts: follow me on Twitter or subscribe to my RSS feed

October 26th, 2006 at 10:05 am
What is the best way to construct classes in Javascript?
October 26th, 2006 at 10:14 am
Hi Marcel, I don’t know the best way, but I find myself using option 2 most of the time.
November 1st, 2006 at 2:48 pm
What advantage is there to using method 2 over method 1/1.1? I understand that most of the time when programming for the web a singleton will do, but is there some benifit to using method 2 compared to method 1/1.1?
November 1st, 2006 at 3:55 pm
Well, compared to 1, you have less in the global namespace, that’s good.
Compared to 1.1., you have one global var in the namespace, as opposed to one global function, which is pretty much the same.
Using method 2 you can also define your own namespace, just like Y! did with their YUI and the YAHOO namespace.
June 5th, 2008 at 11:54 pm
This is very goog note about creating object and using them.
I like Second one .
Thanks…..
August 22nd, 2008 at 9:29 am
Very usefully article, i was really crazy about the different ways to write a JavaScript classes, thanx so much for the article!
October 2nd, 2008 at 10:09 am
Stoyan: You can tweak method 1 to get namespaced classes.
window.Namespace = {};
Namespace.Apple = function(type){ … }
var apple = new Namespace.Apple(‘macintosh’)
Then, instead of defining new functions in the global scope, you should add them to your class’ prototype. E.g.
Namespace.Apple.prototype.getInfo = function(){…}
Your method of adding functions in methods 1.1, 2, and 3 works, but it is not ideal compared to using the prototype. This is because the prototype is a shared object amongst all Apple instance. Creating a new function for each object is doing just that; for 5 Apple objects, you have 5 different getInfo functions, but by using the prototype, you have only one.
October 3rd, 2008 at 5:22 am
Most of the time I use 2. Since javascript is prototypal , I find myself using clone rather than using classes and objects.
eg. var sample = { .. }
var obj1 = clone(sample)
var obj2 = clone(sample)
Most JS frameworks provide a decent implementation of clone.
October 5th, 2008 at 12:44 am
Concerning the way laid out in method #1, both of the examples have issues. As you pointed out for the base case, you end up with an additional function defined in the global namespace that is unnecessary. For the example in 1.1, however, you will end up with a separate copy of the function for each and every instance of the class, which is simply wasted memory, since the function is identical in each instance. The best way to define methods for classes in this method is to define them outside of the constructor function itself, but as attributes of its prototype. This can be done fairly simply as follows, and solves both issues:
Apple.prototype.getInfo = function() {
return this.color + ‘ ‘ + this.type + ‘ apple’;
}
April 12th, 2009 at 3:56 am
[...] PS: Recentemente ho trovato questo link che sipega tutte le notazioni: http://www.phpied.com/3-ways-to-define-a-javascript-class/ [...]
April 26th, 2009 at 1:34 am
[...] do you make classes and objects in javascript? http://www.phpied.com/3-ways-to-define-a-javascript-class/ [...]
May 7th, 2009 at 8:02 pm
[...] 3 ways to define a JavaScript class / phpied.com Good read – ways to define JS Class (tags: objects reviews development tutorial) [...]
May 8th, 2009 at 5:08 am
Great solutions! Thanks!
May 8th, 2009 at 4:10 pm
[...] 3 ways to define a JavaScript class – Stoyan Stefanov (Suggested by Elijah Manor) [...]
May 20th, 2009 at 10:00 am
The disadvantage of method 2 is that it will use more memory since the function will be recreated every time, while in method 1 all object-instances share the same copy of the function.
May 20th, 2009 at 10:00 am
Method 1.1 vs. method 1 that is.
May 21st, 2009 at 10:55 am
The best/proper way to create a custom class in javascript is to use the prototype object.
function myClass(opts){
//constructor here
}
myClass.prototype.myMethod=function(){
//method logic here
}
That is sort of a mix between your methods 1 and 1.1. The global namespace is left unscathed by the method as in your option 1, and there is no unnecessary memory used like in your option 1.1.
To declare multiple properties and methods in the prototype, create a JSON object like your option 2.
myClass.prototype = {
myProperty:”this is a string”,
myMethod:function(parms){
//method logic here
}
}
Then you create a new instance of the class by … var instance = new myClass();
Hope this helps!
May 25th, 2009 at 5:55 am
Interesting post, although a quick note about method 2 “Using JSON” technically that example is using javascript object literal notation and not JSON. JSON is a subset of object literal notation, designed to be a data interchange medium, by its definition it only holds data and not operations on data (ie no functions) – like you have used in your example. Its a subtle but important point to make, read more about JSON here http://www.json.org/fatfree.html.
June 2nd, 2009 at 10:59 pm
The above Stuff & Discussion is good..!
Is possible to create our own framework in javascript using method 2?
If so, can any one explain?
June 26th, 2009 at 1:43 pm
Nice article!!!
One thing is that your JSON section is a little misleading. It’s not JSON syntax that you are using–instead what you are doing is defining a map (also called a dictionary in some languages) variable. All JavaScript objects are maps, that’s why you can iterate over all of the members of an object using the “for (var m in obj)” syntax..
I hope that makes JavaScript seem even more cool to you!
July 14th, 2009 at 11:49 pm
great work…………
thanks for the article…………..
can you please explain me how to define a constructor for these classes
September 12th, 2009 at 3:11 am
[...] 3 Way to define a javascript class [...]
September 28th, 2009 at 1:30 am
Very very useful! Thank you!
October 13th, 2009 at 7:04 am
Thank you buddy,
It is really a nice piece of information.
November 23rd, 2009 at 8:30 am
It’s alarming how many people here are thanking you for giving bad advice. Defining the methods in the constructor is a bad bad thing. It was already mentioned by Steve Streza and Stephen Rushing but I simply do it again: When you define the functions in the constructor then NEW functions are created everytime you create an instance of this class. Assume we have a class with 20 methods in it and create 100 instances of it. Then we have 2000 functions in memory. With proper OO it’s only 20 and it will stay at 20 no matter how many instances you create.
OO in JavaScript is done with prototypes. A class is nothing else than a function and methods are simply functions defined in the prototype of the class.
function MyClass()
{
}
MyClass.prototype.doSomething = function()
{
};
I strongly suggest that you update your blog article and stop teaching other people a wrong way to do OO in JavaScript.
December 16th, 2009 at 2:07 pm
@Klaus defining a function in the constructor is necessary to access private members or methods
function Person() {
//private
var secretMessage = ‘secret’;
this.setSecretMessage = function (msg) {
secretMessage = msg;
}
this.getSecretMessage = function () {
return secretMessage;
}
}
Person.prototype.tryToGetSecretMessage = function () {
// You can’t, this does not share scope with the closure
return secretMessage;
};
December 22nd, 2009 at 10:08 am
Hi,
I think Klaus Reimer said right.
@stfu your exemple should be :
(you need to use this.secretMessage indeed of var secretMessage)
function MyClass(msg)
{
this.secretMessage = msg ;
}
MyClass.prototype.ShowValue = function ()
{
alert(this.secretMessage) ;
}
var t1 = new MyClass(‘hello’) ;
var t2 = new MyClass(‘bye’) ;
t1.ShowValue() ;
t2.ShowValue() ;
You will get messagebox with value “hello” and “bye”.
December 25th, 2009 at 2:24 pm
@David Montandon: You missed the point. “this.secretMessage” becomes publicly readable and modifiable in your example. That’s why it’s declared with var instead.
December 25th, 2009 at 5:20 pm
thx for this,,, is clear and soo understandable!
January 9th, 2010 at 7:38 am
Good ways of defining an Object
February 5th, 2010 at 1:43 pm
To the writer of this article: Your second option is not JSON, as some of the previous comments have also pointed out; you’re using what is called object literal notation. A similar concept is the array literal “var arr = []“, or function literal “function() {…}”. JSON is supposed to be strictly for transporting data.
@klaus
@david
Your code does not allow for private methods or properties. Read about the ‘module pattern’: http://yuiblog.com/blog/2007/06/12/module-pattern/
March 4th, 2010 at 6:34 pm
Nice article, but as others have mentioned, you should include using the prototype object, since that’s probably the best way to add methods to classes.
May 29th, 2010 at 8:48 pm
thnx man, happy JavaScripting indeed !
June 23rd, 2010 at 7:37 pm
Hi all,
I read through this thread. Lots of interesting discussion. It would be really useful if someone (Stoyan?) were to update the original article to incorporate some of the suggestions/discussion.
July 8th, 2010 at 2:34 am
Good discussion, Thanks to all… but what is the best approach? I noticed that @klaus way is right.. but what about for private members and methods?
July 20th, 2010 at 6:41 pm
This is my comment to this: http://gist.github.com/483786
August 14th, 2010 at 3:41 am
Yeah, as others have stated, that’s not JSON.
As you can see in json.org the spec doesn’t mention the use of “function” which you use, thus it’s not JSON.
October 7th, 2010 at 4:50 pm
“Your code does not allow for private methods or properties.”
Its javascript. What’s the point of making properties private? The code isn’t compiled anyway!
October 26th, 2010 at 4:26 am
Yes, JS is not compiled. But what it has to do with encapsulation? Encapsulation is not for security reasons or compilation, but for the programmers to reduce mistakes and facilitate debugging. When your data are private, only private methods can access it. So if there’s a bug with that data, you are sure that it can be located only in some of the private methods, because no one else can access it.
There’s other reason: Creating good interfaces. With encapsulation you can hide all the dangerous details under the hood and the user of your class doesn’t have to worry about these implementation details. The only thing that interests him is the public interface.
But this is not only for the convenience and readability. This also means that user’s code won’t depend on the implementation code, so you can easily change the implementation without worrying users and breaking their existing code. And THAT’s the biggest advantage of encapsulation.
Sadly, JavaScript isn’t object oriented enough to understand that. These “objects” it supports are merely “baskets for data” and some hacks to achieve a cheap imitation of object orientedness.
November 3rd, 2010 at 9:00 am
hey thanks! seems to be really easy – i like the second method too!
November 10th, 2010 at 8:34 am
I sure hope that you wipe this tutorial and its comments and try it again. It seems obvious to me from the comments that there are numerous benefits to using prototype methods (which aren’t addressed at all in your article) and that you don’t understand the use of JSON. The problem is that there are so many comments that obfuscate your original article that it renders useless any intent you may have originally had when posting. In other words, your article and the numerous comments serve more to confuse me than to help me. Now I have to sort through both your article and the 44 comments before this one just to find the best way to implement object notation in my javascripts.
You have a great talent for writing and I am sure that you have better js skills to date, so please, rewrite this article, wipe the comments, and start again. It would be really useful to a lot of us. Thanks for your time and consideration.
jase
November 23rd, 2010 at 11:51 am
Jason, what a prick
December 3rd, 2010 at 12:53 pm
[...] order for this to make sense you’re going to want to already understand how to write a class in JavaScript and you’re going to want to understand [...]
December 22nd, 2010 at 8:20 am
Thank you very much. Its really usefull.
January 29th, 2011 at 4:42 pm
I have to concur with Jason’s posting above. Stoyan’s excellent book “Javascript Patterns” makes it clear his understanding of Javascript and JSON has moved way beyond the recommendations and comments he made in this now over 4 year old article. I recommend to anyone that they check out his book for the real story on how all this works, and better recommendations of good practices.
February 6th, 2011 at 12:58 am
Thanks Stoyan’s article and Tim’s comment, very very useful!!
March 4th, 2011 at 9:12 pm
Thanks for the comments everyone! Finally managed to update the article and correct some (hopefully all) mistakes.
March 10th, 2011 at 7:31 am
Well explained Article Stoyan.
And check this link http://www.sayopenweb.com/inheritance-in-javascript/ for javascript inheritance.
March 10th, 2011 at 3:45 pm
Great article and also great discussion.
But, How can I do to define a Singleton using Object Literals (I prefer JSON-like way) and Implementing a default constructor ?
Thanks !
March 11th, 2011 at 12:35 pm
[...] http://www.phpied.com/3-ways-to-define-a-javascript-class/ This entry was posted on Saturday, March 12th, 2011 at 1:36 amand is filed under web, 編程. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site. [...]
May 5th, 2011 at 6:39 pm
[...] Heck, even I have this "how to define a JavaScript class" post on my other blog. I wrote it years ago when, coming from PHP, I was curious how stuff works [...]
May 23rd, 2011 at 12:17 pm
Thanks so much! You made the subject so clear in a few paragraphs. Great Job!
May 24th, 2011 at 6:04 am
Thanks for this article. (I read it after the changes asked by the others) It was very useful.
May 25th, 2011 at 6:03 pm
[...] 3 ways to define a JavaScript class / Stoyan's phpied.com (tags: javascript programming class oop classes tutorial json js) [...]
May 27th, 2011 at 5:00 pm
Post’s don’t work?
May 27th, 2011 at 5:01 pm
Hmm, it seems to work, after a few 404′s, i am trying again.
This is the way i prefer, i combined some techniques over the years…
// define namespace
var Employers = {};
Employers.getInstance = (function() {
return Employers;
})();
// general employee class
Employers.Employee = function(){
var Private, Public;
Private = Public = {};
Public.setName = function(name) {
Private.name = name;
}
Public.getName = function() {
return Private.name;
}
return Public;
};
// Alpha
Employers.Alpha = (function(Super){
var Private, Public;
Private = Public = {};
Private.Employee = new Super.Employee;
Public.setName = function(name) {
Private.Employee.setName(name);
}
Public.getName = function() {
console.log(‘Alpha: [' + Private.Employee.getName() + ']‘);
}
return Public;
})(Employers.getInstance);
// Beta
Employers.Beta = (function(Super){
var Private, Public;
Private = Public = {};
Private.Employee = new Super.Employee;
Public.setName = function(name) {
Private.Employee.setName(name);
}
Public.getName = function() {
console.log(‘Beta: [' + Private.Employee.getName() + ']‘);
}
return Public;
})(Employers.getInstance);
Employers.Alpha.setName(‘Alpha’);
Employers.Beta.setName(‘Beta’);
Employers.Alpha.getName();
Employers.Beta.getName();
/*
output:
Alpha [Alpha]
Beta [Beta]
*/
June 15th, 2011 at 7:43 pm
What’s with function($) that you see everywhere? Same as function()?
July 2nd, 2011 at 1:24 am
[...] Javascript classhttp://www.phpied.com/3-ways-to-define-a-javascript-class/ [...]
August 3rd, 2011 at 11:41 pm
[...] 3 ways to define a JavaScript class [...]
August 9th, 2011 at 10:44 pm
I see absolutely no classes defined anywhere in this article OR its comments.
Not even one.
September 5th, 2011 at 4:56 pm
@Function Objects:
Javascript (rather annoyingly) doesn’t have a “class” keyword as C++/Java/C#/etc. do, so we have to synthesize the essentials of a class by declaring a function() to encapsulate properties and functions.
October 1st, 2011 at 4:58 pm
Nice way to create class in javascript is using this library:
http://code.google.com/p/jsclassextend/
simple:
var SomeClass = JS.Class({
//class body
});
October 14th, 2011 at 10:47 am
Muy util, sinceramente me sirvio. existia una manera que jamas habia comprendido. Excelente trabajo.
November 11th, 2011 at 12:14 pm
thank you so much, coming from an object oriented programming, this helps out sooo muchoo.. Salamat!
November 13th, 2011 at 8:29 am
[...] 원문 : 3 ways to define a JavaScript class http://www.phpied.com/3-ways-to-define-a-javascript-class/ [...]
November 16th, 2011 at 1:50 am
i was frightened…
November 18th, 2011 at 6:05 pm
Very nice article.
Simple, crisp and clear.
Great job.
November 23rd, 2011 at 5:45 am
Excellent article – thanks for the effort.
December 9th, 2011 at 11:07 am
[...] even I have this “how to define a JavaScript class” post on my other blog. I wrote it years ago when, coming from PHP, I was curious how stuff [...]
December 15th, 2011 at 12:46 am
For 2: this also working using double quotes
var apple = {
“type”: “macintosh”,
“color”: “red”,
“getInfo”: function () {
return this.color + ‘ ‘ + this.type + ‘ apple’;
}
}
December 24th, 2011 at 8:44 pm
This is one of the best explanations ever. To me, the original version had even more value than the update one because it ended up flushing out an ever more valuable discussion of the pros and cons of the various methods. Excellent job Stoyan and everyone else who contributed. Thanks.
December 29th, 2011 at 6:09 am
thanx.. very nice description…
December 29th, 2011 at 6:13 am
what is way to execute method in parent class which is overrided in child class? Thanx in advance..
January 3rd, 2012 at 1:24 am
[...] http://www.phpied.com/3-ways-to-define-a-javascript-class/ This entry was posted in Genel. Bookmark the permalink. ← fcbkcomplete [...]
January 6th, 2012 at 2:19 pm
Wonderful work! That is the kind of info that should be shared across the internet. Shame on Google for now not positioning this put up higher! Come on over and discuss with my web site . Thank you =)
January 9th, 2012 at 8:29 pm
A better alternative to 3, new function is to return an object literal from within a function, eg
var apple = function () {
return {
type: ‘macintosh’,
color: ‘red’,
getInfo: function () {
return this.color + ‘ ‘ this.type + ‘ apple’;
}
};
}
as per http://yuiblog.com/blog/2006/11/13/javascript-we-hardly-new-ya/
January 12th, 2012 at 2:37 pm
I usually use method 1.2, with the prototypes directly underneath the main function, but indented a step further. It tricks me into thinking I am using python-like classes (which I like)
January 13th, 2012 at 5:28 pm
Thanks man… you saved the day.
// anti-pattern! keep reading…
THIS LINE OF YOURS show that you understand programmers well and you are a good writer..
January 18th, 2012 at 4:07 pm
[...] I am back to thinking it’s a pretty cool scripting language. That is mainly thanks to an excellent blog post by Stoyan Stefanov, all about doing classes in Javascript. Everything is an object, so of course we don’t need a [...]