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 [...]
February 5th, 2012 at 6:49 pm
well then wtf is it when they put
”
(function(){
…
})
”
as per several advanced javascript files, including jquery, that I’ve seen.
February 7th, 2012 at 5:34 am
Great article….simple and informative.
thnx
February 7th, 2012 at 10:21 am
Awesome article. Everything you need to know, in as many words as necessary.
February 16th, 2012 at 7:31 am
The 2 is the beswt way to me. I enjoyed this article, my friend!
Rodolfo Jorge Nemer Nogueira
Rodolfo Jorge Nemer Nogueira
Curitiba Paraná
February 21st, 2012 at 5:57 am
Thanks for a fine article on creating javascript class. Helped me a lot.
February 28th, 2012 at 6:18 am
[...] To define classes in javascript as a object oriented pattern, please visit http://www.phpied.com/3-ways-to-define-a-javascript-class/ [...]
March 10th, 2012 at 3:02 am
Second way is not working in my computer.. is there any browser dependency issues with it?
March 13th, 2012 at 4:48 am
Oh man! What class, where did You find class in javascript. LOL
That’s embarrassing!!!!
March 29th, 2012 at 3:43 am
[...] more ways to define 'classes' using JavaScript, see Stoyan Stefanov's useful post on [...]
April 5th, 2012 at 10:56 am
[...] Author: John Resig3 ways to define a JavaScript classhttp://www.phpied.com/3-ways-to-define-a-javascript-class/ Author: Stoyan StefanovPrinciples of Writing Consistent, Idiomatic [...]
April 10th, 2012 at 7:10 am
very thanks to let me understand the basics of different way of object creation.Once again thanks its very helpful.
April 25th, 2012 at 3:27 am
The second way looks pretty clean, but how do I handle parameters into it?
The example only shows setting “members” to hard-coded values.
April 25th, 2012 at 3:00 pm
This is the best web programming page, on any subject, I have ever seen. The information is concise and informative. Clearly not written by a web programmer newbie who just wants to look smart.
April 30th, 2012 at 4:11 pm
Good stuff man!
April 30th, 2012 at 5:35 pm
But what happens when you do:
var apple = {…};
var orange = apple;
It doesn’t clone, and it doesn’t exactly reference – it creates a copy of a reference.
What about this?
var orange = apple.prototype;
May 1st, 2012 at 2:08 pm
[...] Click to know more [...]
May 2nd, 2012 at 1:33 pm
Création site internet | Web Design | Programmation | Flyers [ Web Agence informatique...
[...]3 ways to define a JavaScript class / Stoyan’s phpied.com[...]…
May 3rd, 2012 at 12:28 am
[...] more ways to define ‘classes’ using JavaScript, see Stoyan Stefanov’s useful post on [...]
May 9th, 2012 at 4:53 am
Great article!
May 12th, 2012 at 6:30 am
Nice article! – Lovin the added discussion points!!
)
It’s clear that there are multiple ways to implement a “class” in javascript and the onus is on the developer to try to utilise the best requirement at the time.
Stoyan originally set out to communicate to other developers how to read and understand how other people have implemented classes within javascript!
Personally I consider that job done! Thanks Stoyan!
Olly
May 30th, 2012 at 5:46 am
[...] the above have been taken from http://www.phpied.com/3-ways-to-define-a-javascript-class/ Category: Uncategorized [...]
June 8th, 2012 at 5:24 pm
[...] Please be aware that although I’m talking about classes, JavaScript doesn’t actually support real classes in the sense like how classes work in C++, Java, Python, [...]
June 15th, 2012 at 10:49 pm
I don’t know if anyone mentioned this in the comments but you can actually create an instance of an object literal. The code is in “JavaScript: The Good Parts”.
It works because you can choose which prototype your object uses and it can use an object literal as its prototype.
if(typeof Object.create !==’function’){
Object.create = function(o){
var F = function(){};
F.prototype = o;
return new F();
};
var new_object = Object.create(object_literal);
June 20th, 2012 at 12:54 pm
I suggest some of you read the Wiki page on JSON.
I quote:
JavaScript syntax defines several native data types not included in the JSON standard:[7] Date, Error, Math, Regular Expression, and Function. These JavaScript data types must be represented as some other data format, with the programs on both ends agreeing on how to convert between types.
http://en.wikipedia.org/wiki/JSON
Therefore, JSON is a bastardised version of JSOLN (literal) and considering that ALL that lovely fixed data is considered literal. Obviously we have some people who are blagging the art of programming.
I would also like to quote this:
In computer science, a literal is a notation for representing a fixed value in source code. Almost all programming languages have notations for atomic values such as integers, floating-point numbers, strings, and booleans; some also have notations for elements of enumerated types and compound values such as arrays, records, and objects.
http://en.wikipedia.org/wiki/Literal_(computer_programming)
You guys obviously spend too much time comparing the sizes of your e-peens.
July 10th, 2012 at 9:43 am
Thank you so much.
July 24th, 2012 at 3:05 am
Comment
July 25th, 2012 at 2:49 am
[...] Fonte: http://www.phpied.com/3-ways-to-define-a-javascript-class/ [...]
August 7th, 2012 at 9:45 am
[...] have seen a lot of examples of prototyping and libraries for simulating classes in JavaScript, some of them is really nice but [...]
August 8th, 2012 at 6:08 pm
[...] By the way, using backbone.js also forces you to adhere to the above conventions! Sources: http://www.phpied.com/3-ways-to-define-a-javascript-class/ http://kangax.github.com/nfe/ [...]
August 21st, 2012 at 1:46 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 [...]
August 28th, 2012 at 2:41 am
Interesting article. Exactly what I needed. Superb discussion in the comments section as well.
August 29th, 2012 at 4:34 pm
Great article! That’s exactly what I needed, now trying to code a mobile project using MVC, thank you!
August 31st, 2012 at 6:30 am
Good Article
September 3rd, 2012 at 4:18 am
[...] A really good explaination about Objects is posted here [...]
September 7th, 2012 at 9:38 pm
Thank you so much for this explanation! Before I read this article I felt like my head was gonna explode trying to understand function declaration in OOP, now I know what to do exactly and it’s finally so clear
Thank you so much!
September 11th, 2012 at 3:24 am
[...] http://www.phpied.com/3-ways-to-define-a-javascript-class/ #crayon-504ef567ed645 .crayon-plain { font-size: 12px !important; line-height: 16px !important; } <code>var panel = { init: function () { alert("Hello!"); } } panel.init();</code> [...]
September 25th, 2012 at 2:49 am
Good work. You explained it well.
October 6th, 2012 at 2:50 pm
http://www.johnythegame78r2.com
October 9th, 2012 at 12:18 pm
[...] 3 ways to define a JavaScript class [...]
October 21st, 2012 at 12:31 pm
Thanks, this was a really good explanation of the concept, and cleared up my confusion.
October 23rd, 2012 at 2:52 pm
Good post. Now I’m much more organized…
October 25th, 2012 at 11:41 am
I don’t understand the functional difference between #2 and #3. Why would you use one over the other?
October 27th, 2012 at 1:07 pm
Thanks for the article! It helped me a lot to get a clearer picture of how js objects work.
November 1st, 2012 at 1:36 pm
Why so many comments blame the method 2.?
The author said numerous times that method 2 is to create a singleton! (singleton = unique instance). Therefore there won’t be N copies of the functions…
Besides, great explanations. Thanks.
November 10th, 2012 at 8:37 am
Nice tutorial, now I understand class in javascript
Thanks
December 13th, 2012 at 7:05 am
As simple as it could be. Good work
December 20th, 2012 at 10:15 am
[...] is the lack of object functionality compared to other languages, especially Java and C++. Although there are ways to create an object with its own variables and functions, there are no visibility modifiers. [...]
December 29th, 2012 at 7:24 pm
January 11th, 2013 at 11:50 pm
Hey , Thank you so much , no body ever explained it in this simple way.
January 17th, 2013 at 8:38 pm
I do accept as true with all of the concepts you’ve introduced for your post. They are very convincing and can certainly work. Nonetheless, the posts are too quick for novices. Could you please extend them a bit from next time? Thanks for the post.
January 25th, 2013 at 10:32 pm
Thanks, it help me a lot.
January 29th, 2013 at 6:56 am
thanks a lot.
January 29th, 2013 at 6:58 am
i translate this article into korean.
i hope it helps many korean developers
한국어로 번역했습니다.
한국 개발자분들 도움되셨음 좋겠어요.
http://steadypost.net/post/lecture/id/13/
March 4th, 2013 at 6:47 am
I wouldn’t say that object literals are a way to define classes in javascript. They are a way of instantiating maps, if you think about it.
March 10th, 2013 at 11:15 am
Hi there! Someone in my Facebook group shared this site with us so I came to give it a look.
I’m definitely loving the information. I’m bookmarking and will be tweeting
this to my followers! Outstanding blog and amazing design and style.
March 12th, 2013 at 3:20 am
[...] generar un código homogéneo para toda la aplicación, evitando así la mezcla de alguna de las 3 formas de declarar clases que existen en [...]
March 17th, 2013 at 10:41 pm
certainly like your website but you need to take a look at the spelling on several of your posts. Several of them are rife with spelling issues and I in finding it very bothersome to tell the reality nevertheless I’ll certainly come back again.
March 18th, 2013 at 7:39 am
I’m really enjoying the design and layout of your website. It’s a very easy on the eyes which makes it much more enjoyable for
me to come here and visit more often. Did you hire
out a developer to create your theme? Outstanding work!
March 20th, 2013 at 5:13 am
sdf sfdgbsgs sfghdtyjndny dhjfju fnghjfgkj fngdfbdj fgjfrtyjkryufr fdghdrtfgd dghdhbn xdfghdshdfb xgd dnhdjdgh fhgjfhc cgd cgndgn dgndgndsfgn fgsfbdfb sdfggh dhgbhsd
April 5th, 2013 at 5:45 am
Thank you for explanation
April 9th, 2013 at 11:19 pm
continuously i used to read smaller articles or reviews that as well clear their motive, and
that is also happening with this paragraph which I am reading now.
April 13th, 2013 at 6:14 pm
I think this is among the most vital info for me. And i’m glad studying your article. But want to commentary on some basic issues, The web site taste is ideal, the articles is really great : D. Excellent task, cheers
April 16th, 2013 at 11:27 am
I’m in favor of the more “pure” use of prototypes for inheritance. And we don’t need to stash all our privates in the constructor if we wrap our declaration in an AMD closure. See? It’s possible to be both hip and contemporary and observe decent traditions.
Learn from old and new and find what’s best. And remember the _briefest_ way to write code is not always the most _optimal_.
April 18th, 2013 at 1:10 am
Hello,
Will you please tell what is meant by :
“A drawback of 1.1. is that the method getInfo() is recreated every time you create a new object.”
How to check it?What is meant by recreated?
As we used to give alert in getInfo() not getting displayed untill and unless we used to call it explicitly.
Thanks in advance.
April 18th, 2013 at 7:02 pm
Ahaa, its nice conversation about this piece of writing here
at this webpage, I have read all that, so now me also commenting at this
place.
May 1st, 2013 at 12:44 pm
Hmm it seems like your site ate my first comment (it was super long)
so I guess I’ll just sum it up what I submitted and say, I’m
thoroughly enjoying your blog. I too am an aspiring blog blogger but I’m still new to the whole thing. Do you have any points for rookie blog writers? I’d genuinely appreciate it.
May 2nd, 2013 at 3:40 pm
Hello would you mind letting me know which webhost you’re using? I’ve loaded your blog in 3
different web browsers and I must say this blog loads a lot quicker then most.
Can you recommend a good internet hosting provider at a reasonable price?
Thanks a lot, I appreciate it!
May 2nd, 2013 at 9:42 pm
Since the admin of this site is working, no uncertainty very rapidly it
will be famous, due to its feature contents.
May 5th, 2013 at 9:29 am
Hi Stoyan, I like the way you explained the creation of objects. I am beginner for advance Javascript. I will always be following your articles for help. Great work.
May 8th, 2013 at 9:07 pm
I’m not sure exactly why but this blog is loading very slow for me. Is anyone else having this issue or is it a issue on my end? I’ll check back later on and
see if the problem still exists.
Look into my site – free visa gift card
May 13th, 2013 at 12:09 am
Hi there, just changed into alert to your blog thru Google, and located that it’s really informative. I am going to watch out for brussels. I’ll be grateful if you proceed this in future. Many folks will probably be benefited out of your writing. Cheers!
May 14th, 2013 at 5:28 am
Hey there would you mind stating which blog platform you’re using? I’m
looking to start my own blog soon but I’m having a hard time selecting between BlogEngine/Wordpress/B2evolution and Drupal. The reason I ask is because your design and style seems different then most blogs and I’m looking for something unique.
P.S Sorry for getting off-topic but I had to ask!
May 14th, 2013 at 1:41 pm
Appreciate your one more great report. The area different could anyone obtain that form of facts in this a good way involving writing? I’ve got a demonstration next week, for in the hunt for such information.
May 16th, 2013 at 11:26 pm
You need to be a part of a contest for one of the highest quality websites on the
web. I most certainly will recommend this blog!
May 20th, 2013 at 2:24 am
Hi! I’ve been reading your website for a long time now and finally got the courage to go ahead and give you a shout out from Lubbock Texas! Just wanted to say keep up the great job!