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

154 Responses to “3 ways to define a JavaScript class”

  1. Marcel Says:

    What is the best way to construct classes in Javascript?

  2. Stoyan Says:

    Hi Marcel, I don’t know the best way, but I find myself using option 2 most of the time.

  3. Patrick Says:

    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?

  4. Stoyan Says:

    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.

  5. Rakesh Patel Says:

    This is very goog note about creating object and using them.
    I like Second one .
    Thanks…..

  6. Claudio Says:

    Very usefully article, i was really crazy about the different ways to write a JavaScript classes, thanx so much for the article!

  7. Steve Streza Says:

    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.

  8. a Says:

    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.

  9. Kent Says:

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

  10. Programmazione Object Oriented in JavaScript « Il blog di Nicola Amatucci Says:

    [...] PS: Recentemente ho trovato questo link che sipega tutte le notazioni:  http://www.phpied.com/3-ways-to-define-a-javascript-class/ [...]

  11. Here are some javascript references Jav… « Crawlicious Says:

    [...] do you make classes and objects in javascript? http://www.phpied.com/3-ways-to-define-a-javascript-class/ [...]

  12. Daily Links | AndySowards.com :: Professional Web Design, Development, Programming, Hacks, Downloads, Math and being a Web 2.0 Hipster? Says:

    [...] 3 ways to define a JavaScript class / phpied.com Good read – ways to define JS Class (tags: objects reviews development tutorial) [...]

  13. Pavlov.org Says:

    Great solutions! Thanks!

  14. Technology Related Links for May 8th, 2009 - Jason N. Gaylord's Blog Says:

    [...] 3 ways to define a JavaScript class – Stoyan Stefanov (Suggested by Elijah Manor) [...]

  15. Javache Says:

    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.

  16. Javache Says:

    Method 1.1 vs. method 1 that is.

  17. Stephen Rushing Says:

    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!

  18. Nigel Thomas Says:

    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.

  19. Viswanathan Says:

    The above Stuff & Discussion is good..!
    Is possible to create our own framework in javascript using method 2?
    If so, can any one explain?

  20. firefight Says:

    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! :)

  21. Revath S Kumar Says:

    great work…………
    thanks for the article…………..
    can you please explain me how to define a constructor for these classes

  22. 書籤紀錄 Says:

    [...] 3 Way to define a javascript class [...]

  23. Matjaz Says:

    Very very useful! Thank you!

  24. Amit Verma Says:

    Thank you buddy,
    It is really a nice piece of information.

  25. Klaus Reimer Says:

    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.

  26. stfu Says:

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

  27. David Montandon Says:

    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”.

  28. Rick Says:

    @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.

  29. iim.hlk Says:

    thx for this,,, is clear and soo understandable!

  30. Nanda Says:

    Good ways of defining an Object

  31. nietzsche Says:

    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/

  32. Peter Says:

    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.

  33. Gassan Says:

    thnx man, happy JavaScripting indeed !

  34. SuperFast Says:

    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.

  35. shahrzad Says:

    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?

  36. mfolnovic Says:

    This is my comment to this: http://gist.github.com/483786 :)

  37. Alfred Morgan Says:

    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.

  38. anon Says:

    “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!

  39. SasQ Says:

    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.

  40. Kim Says:

    hey thanks! seems to be really easy – i like the second method too!

  41. Jason Says:

    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

  42. DumbAzzAboveMe Says:

    Jason, what a prick

  43. SplatByte » JavaScript Inheritance Says:

    [...] 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 [...]

  44. samt Says:

    Thank you very much. Its really usefull.

  45. tim Says:

    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.

  46. Luiz Says:

    Thanks Stoyan’s article and Tim’s comment, very very useful!!

  47. Stoyan Says:

    Thanks for the comments everyone! Finally managed to update the article and correct some (hopefully all) mistakes.

  48. Sayooj Says:

    Well explained Article Stoyan.

    And check this link http://www.sayopenweb.com/inheritance-in-javascript/ for javascript inheritance.

  49. Pepe Says:

    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 !

  50. [web][js] 3 ways to define a JS Class | CODE@蝴蝶。夢 Says:

    [...] 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. [...]

  51. JSPatterns.com » Blog Archive » JavaScript classes Says:

    [...] 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 [...]

  52. Chris Says:

    Thanks so much! You made the subject so clear in a few paragraphs. Great Job!

  53. AO Says:

    Thanks for this article. (I read it after the changes asked by the others) It was very useful.

  54. Buzz Lightyear is here » Blog Archive » links for 2011-05-25 Says:

    [...] 3 ways to define a JavaScript class / Stoyan's phpied.com (tags: javascript programming class oop classes tutorial json js) [...]

  55. Barry Says:

    Post’s don’t work?

  56. Barry Says:

    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]
    */

  57. John Fro Says:

    What’s with function($) that you see everywhere? Same as function()?

  58. Javascript class « tediscript.wordpress.com Says:

    [...] Javascript classhttp://www.phpied.com/3-ways-to-define-a-javascript-class/ [...]

  59. Most Beautiful Tut on Object Oriented Programming with javaScript « Niroze's Weblog Says:

    [...] 3 ways to define a JavaScript class [...]

  60. Function Objects Says:

    I see absolutely no classes defined anywhere in this article OR its comments.

    Not even one.

  61. Bitcrazed Says:

    @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.

  62. Wrapper Says:

    Nice way to create class in javascript is using this library:
    http://code.google.com/p/jsclassextend/

    simple:
    var SomeClass = JS.Class({
    //class body
    });

  63. Isaac Trenado Perea Says:

    Muy util, sinceramente me sirvio. existia una manera que jamas habia comprendido. Excelente trabajo.

  64. Mark D Says:

    thank you so much, coming from an object oriented programming, this helps out sooo muchoo.. Salamat!

  65. 자바 스크립트 클래스를 정의하는 세가지 방법 | Inside.JS Says:

    [...] 원문 : 3 ways to define a JavaScript class http://www.phpied.com/3-ways-to-define-a-javascript-class/ [...]

  66. tanku Says:

    i was frightened…

  67. Shanky Says:

    Very nice article.
    Simple, crisp and clear.

    Great job.

  68. Joe Says:

    Excellent article – thanks for the effort.

  69. JavaScript classes Says:

    [...] 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 [...]

  70. vijayface Says:

    For 2: this also working using double quotes
    var apple = {
    “type”: “macintosh”,
    “color”: “red”,
    “getInfo”: function () {
    return this.color + ‘ ‘ + this.type + ‘ apple’;
    }
    }

  71. Zdravko Says:

    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.

  72. prasad Says:

    thanx.. very nice description…

  73. prasad Says:

    what is way to execute method in parent class which is overrided in child class? Thanx in advance..

  74. 3 ways to define a JavaScript class | Karipcin Developer Blog Says:

    [...] http://www.phpied.com/3-ways-to-define-a-javascript-class/ This entry was posted in Genel. Bookmark the permalink. ← fcbkcomplete [...]

  75. inexpensive vps Says:

    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 =)

  76. David Clements Says:

    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/

  77. Matt Says:

    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)

  78. Mubbasher Mukhtar Says:

    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..

  79. Harvest stuff for GSoC: Week 7! | Dylan McCall Says:

    [...] 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 [...]

  80. anonymous Says:

    well then wtf is it when they put

    (function(){

    })

    as per several advanced javascript files, including jquery, that I’ve seen.

  81. mayank Says:

    Great article….simple and informative.
    thnx

  82. Dan Says:

    Awesome article. Everything you need to know, in as many words as necessary.

  83. Rodolfo Jorge Nemer Nogueira Says:

    The 2 is the beswt way to me. I enjoyed this article, my friend!

    Rodolfo Jorge Nemer Nogueira
    Rodolfo Jorge Nemer Nogueira
    Curitiba Paraná

  84. Usama Ahmed Says:

    Thanks for a fine article on creating javascript class. Helped me a lot.

  85. Classes in javascript « Dipak Karki Says:

    [...] To define classes in javascript as a object oriented pattern, please visit http://www.phpied.com/3-ways-to-define-a-javascript-class/ [...]

  86. Sourabh Bajaj Says:

    Second way is not working in my computer.. is there any browser dependency issues with it?

  87. BrightShadow Says:

    Oh man! What class, where did You find class in javascript. LOL
    That’s embarrassing!!!!

  88. Hello, The Cafe » A brief note on classes Says:

    [...] more ways to define 'classes' using JavaScript, see Stoyan Stefanov's useful post on [...]

  89. JavaScript Programming Resources - Wijmo Says:

    [...] 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 [...]

  90. Chidambaram Perumal Says:

    very thanks to let me understand the basics of different way of object creation.Once again thanks its very helpful.

  91. Danny F Says:

    The second way looks pretty clean, but how do I handle parameters into it?

    The example only shows setting “members” to hard-coded values.

  92. Allen Says:

    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.

  93. bryan strader Says:

    Good stuff man!

  94. Aaron Evans Says:

    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;

  95. 3 ways to define a JavaScript class « Frontendboss Says:

    [...] Click to know more [...]

  96. Création site internet | Web Design | Programmation | Flyers [ Web Agence informatique Says:

    Création site internet | Web Design | Programmation | Flyers [ Web Agence informatique...

    [...]3 ways to define a JavaScript class / Stoyan’s phpied.com[...]…

  97. Essential JavaScript & jQuery Design Patterns – web前端开发 Says:

    [...] more ways to define ‘classes’ using JavaScript, see Stoyan Stefanov’s useful post on [...]

  98. sWozzAres Says:

    Great article!

  99. Oliver Forder Says:

    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

  100. Fran Santiago » 3 Ways define a psudo-Class in Javascript Says:

    [...] the above have been taken from http://www.phpied.com/3-ways-to-define-a-javascript-class/ Category: Uncategorized [...]

  101. CoffeeScript: The five minute guide to Classes | Giant Flying Saucer Says:

    [...] 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, [...]

  102. schweeneh Says:

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

  103. Wowee Says:

    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.

  104. Burak TARHANLI Says:

    Thank you so much.

  105. Name Says:

    Comment

  106. Blog Marchio Digitale » Creare una classe in JavaScript Says:

    [...] Fonte: http://www.phpied.com/3-ways-to-define-a-javascript-class/ [...]

  107. Hooked on CoffeeScript « Anton Kallenberg Says:

    [...] have seen a lot of examples of prototyping and libraries for simulating classes in JavaScript, some of them is really nice but [...]

  108. My JavaScript Environment | Parris Studios Says:

    [...] 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/ [...]

  109. JSSpy » Javascript classes Says:

    [...] 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 [...]

  110. Vijay Kanta Says:

    Interesting article. Exactly what I needed. Superb discussion in the comments section as well.

  111. Daniel Says:

    Great article! That’s exactly what I needed, now trying to code a mobile project using MVC, thank you!

  112. sunil Says:

    Good Article

  113. 30 minutes to learn JavaScript | AJ Web Designer :: PHP JavaScript Says:

    [...] A really good explaination about Objects is posted here [...]

  114. Sara Says:

    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! :)

  115. 私のjqueryのコードは動作しません。 なぜですか? | t1u Says:

    [...] 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> [...]

  116. Ali Says:

    Good work. You explained it well.

  117. Renita Stafford Says:

    http://www.johnythegame78r2.com

  118. How to Make JQueryUI Widgets Says:

    [...] 3 ways to define a JavaScript class [...]

  119. SB Says:

    Thanks, this was a really good explanation of the concept, and cleared up my confusion.

  120. Alechandrina Says:

    Good post. Now I’m much more organized…

  121. D Says:

    I don’t understand the functional difference between #2 and #3. Why would you use one over the other?

  122. Flavio Says:

    Thanks for the article! It helped me a lot to get a clearer picture of how js objects work.

  123. Yves Says:

    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.

  124. mot gio Says:

    Nice tutorial, now I understand class in javascript :(
    Thanks

  125. Ali Says:

    As simple as it could be. Good work

  126. jeconom.com | jeconom.com Says:

    [...] 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. [...]

  127. web page Says:

  128. Smily Myra Says:

    Hey , Thank you so much , no body ever explained it in this simple way.

  129. Tutorials|Tips and Tricks|Tech Reviews Says:

    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.

  130. debianick Says:

    Thanks, it help me a lot.

  131. kim Says:

    thanks a lot.

  132. qoo Says:

    i translate this article into korean.
    i hope it helps many korean developers

    한국어로 번역했습니다.
    한국 개발자분들 도움되셨음 좋겠어요.

    http://steadypost.net/post/lecture/id/13/

  133. radu Says:

    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.

  134. how to create a blog Says:

    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.

  135. Primeros pasos con TypeScript | Programando en .net Says:

    [...] 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 [...]

  136. Food City 500 Live Stream Says:

    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.

  137. envios de dinero online Says:

    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!

  138. sdf Says:

    sdf sfdgbsgs sfghdtyjndny dhjfju fnghjfgkj fngdfbdj fgjfrtyjkryufr fdghdrtfgd dghdhbn xdfghdshdfb xgd dnhdjdgh fhgjfhc cgd cgndgn dgndgndsfgn fgsfbdfb sdfggh dhgbhsd

  139. Kineticwing Says:

    Thank you for explanation

  140. Design A Website Says:

    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.

  141. mugs-photo.fr Says:

    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

  142. blakeAlbion Says:

    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_.

  143. nilophar Says:

    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.

  144. cognitive behavioral therapy toronto Says:

    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.

  145. office rental Says:

    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.

  146. Credit Rehabilitation in Corpus Christi Says:

    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!

  147. the smtp2go review Says:

    Since the admin of this site is working, no uncertainty very rapidly it
    will be famous, due to its feature contents.

  148. Krunal Says:

    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.

  149. free visa gift card Says:

    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

  150. blogjav Says:

    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!

  151. Does Boost Your Bust Works? Says:

    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!

  152. powered by search Says:

    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.

  153. free resumes templates Says:

    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!

  154. Grover Says:

    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!

Leave a Reply