JavaScript classes

OK, think of it as a religious flamewar to the likes of "tabs vs. spaces for indentation". Looks like this particular war is currently (at JSConf and NodeConf) even more heated than it should be. Classes vs prototypes. For or against classes.

I personally don't care about the "winner". The thing is that classes currently don't exist in JavaScript. No such thing. However looks like they might in the next iterations of the language (see latest post from Brendan Eich). Some people miss classes so much that they start calling other things classes or come up with some approximation. Problem is, because classes don't exist, people often mean different things when they say "class".

Sometimes they mean "constructor functions". Sometimes they mean a regular object literal (singleton-type thing. Heck, "singleton" is also open for interpretations). Sometimes they mean an object or a function defined using Crockford's module pattern.

Sometimes it's some completely different home-grown (or library-provided) thingie called klass for example (in my "JavaScript Patterns" book I have one example for educational/thought-provoking purposes). It has to be klass, or _class or something weird. Because class is a reserved word. Unused, but reserved. And one day may be full of meaning. See the problem?

I avoid saying "class". It just doesn't exist. Imagine two months down the road ECMAScript comes up with classes. And they will most certainly not be the classes you may mean today (e.g. classes won't be another name for constructor functions, I'm sure).

So any written text/blog/documentation you've produced will become incorrect and even worse - misleading and confusing.

To summarize:

  • saying "class" today is confusing and takes extra effort to process (what do you mean? what was that again? it doesn't really exist and is not defined in the language, so an extra translation step is required)
  • saying "class" today will read plain wrong tomorrow, will confuse and misinform

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 in JavaScript. Well I got it wrong then. But fixed it not too long ago because it was top 1 result in google and Yahoo search for "javascript class" and "javascript classes" and I didn't want to continue contributing to the confusion.

Note 2:
To my regret, I couldn't make it to JSConf (aka the best!) nor NodeConf this year (because all girls and women in my life are born in May and it's impossible to travel) so I may be a little off on the level of flamewarfare, but according to Twitter I'm not.


47 Responses to “JavaScript classes”

  1. Boaz Sender Says:

    I attended JSConf 2011, and I’m at NodeConf right now. There isn’t much of a flamewar here. It seems that everyone is on board with the notion of creating syntactic sugar for doing prototypal inheritance. There might be a ‘html5 washing’ style argument around the semantics of using the word “class”, but that’s not substantive.

    Generally there is a really moving and exciting feeling in the air here around, and the future of the JavaScript community; creating facilities in the language to support a JavaScript core, and coming together to build that core.

  2. Tim Branyen Says:

    I don’t know what I would use classes for that constructor functions don’t already do for me. When I’m writing native code for Node.js modules, the v8 c++ maps classes almost 1:1 to the exposed JavaScript constructors.

    Introducing a class type seems kind of unnecessary.

  3. Alexandre Morgaut Says:

    Well saying “classes don’t exist” in JavaScript is half true…

    True that the specification says: “ECMAScript does not use classes such as those in C++, Smalltalk, or Java”

    But he you read it well, it doesn’t say “does not use classes” but “does not use classes as those …”
    Classes exists in JavaScript, it is just that JavaScript is not class-based but prototype-based.

    In ECMAScript, the Class is an internal property, literally called [[Class]]. Its definition is “A String value indicating a specification defined classification of objects.”
    Not very clear… sure its specification, not a documentation ;-)

    So here more details in the section 8.6.2 (Object Internal Properties and Methods):

    -> The value of the [[Class]] internal property is defined by this specification for every kind of built-in object. The value of the [[Class]] internal property of a host object may be any String value except one of “Arguments”, “Array”, “Boolean”, “Date”, “Error”, “Function”, “JSON”, “Math”, “Number”, “Object”, “RegExp”, and “String”. The value of a [[Class]] internal property is used internally to distinguish different kinds of objects. Note that this specification does not provide any means for a program to access that value except through Object.prototype.toString (see

    When you apply this same toString function on object created via a custom constructor, the returned class is the name of the constructor function.

    So finally, in JavaScript the class of an object is the name of its constructor… For the native Objects.
    Thinking about it, objects created through a constructor is designed by the constructor prototype, and the result of the constructor initialization.

    But well… for any other Object created with “new” the class internal value is always “Object” (see section 13.2.2 [[Construct]]). It is the same result with Object.create(proto)

    That’s ECMAScript… ;-)

  4. Alexandre Morgaut Says:

    Oups… error: “When you apply this same toString function on object created via a custom constructor, the returned class is the name of the constructor function.”

    No it’s only on native object

    but the BOM and the DOM define their own native objects

  5. Ben Nadel Says:

    As someone who is *definitely* guilty of using the term “class” in Javascript, I would be very hesitant to call it “misleading”. After all, if people are trying to wrap their heads around a concept, coming up with familiar terms I think can be more helpful than harmful.

    We could, for instance, make a big deal about when we refer to “methods” vs. “functions” as these are different things. But, I don’t think misusing them is harmful. We are painting a picture of “behavior” and I think that is what is more important.

    For example, when I talk about the prototype chain, I often talk about a “super constructor” – passing initialization off to the prototype constructor. From a technical standpoint, this is totally inaccurate since there is no “super class”. However, for people who have some classical CS training, I think talking about it in familiar terms is helpful to bridge the gap.

    Now, I am not saying that we shouldn’t have a common vocabulary – we definitely should (and I wish I was better about figuring it all out). BUT, I just want to say that I don’t think some leniency in the terminology is going to be harmful.

  6. Sam Bisbee Says:

    Whenever I miss inheritance when working with Javascript I just $.extend().

  7. Axel Rauschmayer Says:

    I’ve resorted to calling them types: an array is an instance of the Array type. Then you can also talk about subtyping and super-types or sub-types.

  8. Hmm, Check This out, Yahoo Web Search Says:

    I cant wait anymore! Yahoo Web Search…

    [...] » Blog Archive » JavaScript classes[...]…

  9. watch movies online free Says:

    watch movies online free…

    [...] » Blog Archive » JavaScript classes[...]…

  10. Finite Element Analysis Says:

    Thank you for sharing with us, I think this website really stands out : D.

  11. uggs for sale Says:

    Pretty decent blog! Have any tips on aspiring writers? I??m about to start my personal blog soon but I??m some lost on everything.

  12. uggs outlet Says:

    i have to buy wireless speakers but it is possible to best brand?**

  13. Alvaro Emmel Says:

    HEY!Whats wrong with a little coo talk,you think its not going through the minds of people in the military after watching the rape of their country coupled with the lack of respect they get from Washington for all their hard work? Cheap GW2 Gold

  14. mjy Says:

    I find one of the most confusing aspects of JavaScript to be the DOM objects, which are said to belong to various “classes” such as Element, HTMLElement, and HTMLBodyElement. These certainly aren’t true classes because JavaScript doesn’t have a ‘class’ construct. They’re not even constructors, which are the nearest thing to classes in current JavaScript. I regard these “class” designations as just a form of documentation, a label that indicates what properties a prebuilt object provides and tells you where to find a description of the object in the documentation. But what a source of confusion!

  15. Marek Says:

    I haven’t attended any JavaScript conferences (reading this comments I think I should start). Regarding confusing part of the language… well I recently wrote: JavaScript Confusing Bits highlighting everything that made me go “WHAT ?!?!?!!”. There is a lot but most important are call and apply magic, no classes, !(arguments instanceof Array) and most importantly inheritance. I have seen at least of dozen ways of doing it and quite different commonly available implementations like: prototype, base, underscore, knockout… and there is more!!! AOUCH!!!

  16. JSSpy » Javascript classes Says:

    [...] Source: [...]

  17. Edwin Yip | dev of LIVEditor Says:

    It’ll be interesting to read about what do you think of TypeScript, which brings c-family style OOP to JS…

  18. cat acne treatment at home Says:

    In Sonnet 18 from Elizabeth Barrett scars’s Sonnet 41 from Sonnets from the Portuguese dramatizes the closeness of the two poems that will be used to show the ability of the dramatic monologue.

  19. ssd cloud servers Says:

    Great work! That is the variety of facts that needs to be shared online. Feel bad for on bing for no lengthier ranking this article greater! Come on in excess of along with consult with my personal site. Many thanks Implies)

  20. Altaf Khatri Says:

    This article contains details about Classes and inheritance in javascript. A good started for object oriented javascript.

  21. askbüyüsü Says:

    Hey very nice web site!! Guy .. Excellent .. Wonderful .. I’ll bookmark your website and take the feeds additionally?I am happy to search out so many useful information here within the put up, we’d like develop extra strategies in this regard, thank you for sharing. . . . . .

  22. you can check here Says:

    all inclusive cruises Gift-Giving IInsert a small doily at the bottom of each dinner
    plate. The stage is able to make do with less blood flow.

    Indeed, all the while learning lessons about patience.
    This idea has been overtaken by a new breed of knitter.
    It’s also worthwhile visiting Vailima where you can also select a combination of what are commonly known as the food processor. For further information including family planning, please visit our premiere website. Many companies provide a lot of foods in large quantities and enjoy with loved ones and really let your hair down.

  23. playstation 4 e3 2013 Says:

    Truly no matter if someone doesn’t understand afterward its up to other users that they will help, so here it occurs.

  24. the pirate bay news november 2012 Says:

    This would be a good sign, even as we had not anticipated to find quite
    definitely fine gold within the stone. Father arrived at Melbourne
    an incredibly sick man, and the man immediately underwent treatment by specialists for his
    throat trouble. On the Early days with the Peak Downs Field from “The Peak Downs Telegraph”.

  25. whiteboard paint Says:

    Hi, I think your site might be having browser compatibility issues.
    When I look at your website in Firefox, it looks fine but when opening in Internet Explorer, it has some overlapping.
    I just wanted to give you a quick heads up! Other then that,
    amazing blog!

  26. Clash Of Clans Attacking Says:

    Picking Painless Methodѕ In Clash of clanѕ

    Herе іs my homepage – Clash Of Clans Attacking

  27. Clash Of clans hack Android Says:

    I am sure this piece of writing has touched all the internet people, its
    really really fastidious post on building up
    new webpage.

  28. scholl express pedi reviews Says:

    scholl express pedi accessories

    Scholl Express Pedi tough skin remover leaves the
    skin feeling soft and clean from your initial use.
    This device is exclusively designed to enable the expert elimination of difficult skin from the feet, proper in comfort of your
    own residence.

    The epidermis on the feet was created to endure the everyday strain of taking walks and standing up.
    Occasionally constant stress or rubbing from poor fitting footwear could result in hard pores and skin to
    build-up. Foot care for healthy feet is important; after all, they are with you for a
    life time.

    Fantastically and anatomically constructed, the Scholl Express Pedi unique roller surface is likely to make it effortless
    to effectively get rid of unattractive and sometimes not comfortable genuinely tough skin properly.
    Tiny microgranuals inlayed in to the Scholl Express Pedi
    roller, very carefully buff aside challenging skin, without resorting to blades.

    To gain your own personal professional-style
    home pedicure, basically roll over the required region with medium to gentle force motions; just replicate often for
    smooth and soft sensation feet. In addition, the Scholl Express
    Pedi is protected through a two years gaurantee promise, and integrated are 2x AA batteries so that
    you could make a start eliminating lifeless skin tissue right away.

    For lovely, silky-soft skin have a peek at the Scholl Express
    Pedi to revitalise the feet. The revolving head will get rid of unwelcome, dry
    skin from toes speedily, owing to mineral micro-grains inlayed inside the head of the product.
    The Scholl Express Pedi is totally risk-free to use.
    There are no sharp edges or blades and it will come full using a safety stop button.

    The Scholl Express Pedi is an all-round professional skin treatment
    device. It’s so simple to use, causes no pain and helps
    you receive the specified benefits of the ideal
    pedicure. For hygeine purposes, antimicrobial treatment gets rid of bacteria present on the roller head.

  29. clash of the clans Says:

    Aren’t you tired of playing the game countless hours in order to generate the items in the game.

    What outcome you get by playing it like 12 hours
    a day. Small amount of items get increase and you’re happy with that.

    What If I tell you that you can generate unlimited gems, resources and other things in the game.
    YES!! Unlimited Items and you will not have to play the
    countless hours in order to beat your friends or family members.

    If you are looking to the way to get a ton of Gems, Elixir & Gold without spending your money,
    then this Clash of Clans Hack website is for you.

  30. anonymous torrent Says:

    It’s easy to get caught up in your own writing and allow it to
    pull you along. As daylight broke from a miserable night a helicopter flew in, dropping a line to get the man to safety.
    Marc Cuban is promoting a whole new movie theatre model not unlike those that are springing up through the country.

  31. Says:

    DASHCOM websites are springing up all around the world.
    s no secret that illegal file sharing remains rampant in lots of
    countries, including the US, however, it may
    not be government interference that eventually leads on the end from the age of illegal downloads.

    The free Lyrics Search app is accessible at the Android Market.

  32. Barbour Says:

    You can find them around the joints where the tendons and muscles attach to the bones,Barbour Jackets. This retained Barbour UK is the main cause for increasing your weight. However,, before buying any of these always remember their purpose of use as computer glasses, or driving glasses or protective eyewear. Wells is the founder of the Idaho Film and Television Institute in Driggs and the organizer of the region’s annual family movie festival called the Spud Fest. Many peope pefe bying thei sho

  33. send and track mass emails to all of your subscribers and customers. Says:

    You ought to be a part of a contest for one of the highest quality websites on the web.

    I will recommend this web site!

  34. louis vuitton sale Says:

    it’s basically not on the idea of everyone’s louis vuitton epi tongue excepting financial institution analystsWomen who recognize the power of those three top secret weapons can accomplish anything they choose to do. Working with her powerful conversation abilities, her capability to barter properly, and her teamwork skills, the sky will be the restrict. Will she become a self-made tycoon? Probably replica louis vuitton wallets not, and to me, that’s as it really should be. Prices are primarily

  35. gucci handbags sale Says:

    there are no specific photos around the bag for the reason that it really is the type of lv bagsMay perhaps eleven 09:23 PMThe home loan curiosity deduction is welfare for people today that have home loans. triggers house rates to become high 2. encourages mal expense three. Teenagers are more complicated because they each have their very own exclusive personalities. One teenager may possibly appreciate a gucci outlet online brand new tunes CD even though an additional wants clothing, jewelry an

  36. Says:

    I’ve been exploring for a little for any high-quality articles or blog
    posts in this sort of area . Exploring in Yahoo I ultimately stumbled upon this site.

    Studying this information So i am glad to show that I’ve a very good uncanny feeling I found
    out just what I needed. I most unquestionably will make certain
    to do not fail to remember this website and give it a glance on a continuing basis.

    Take a look at my web page bike race hack;,

  37. talk to girls how to do it Says:

    Hello there I am so thrilled I found your web site, I really found you by
    mistake, while I was looking on Bing for something else, Anyways I
    am here now and would just like to say thanks for
    a marvelous post and a all round interesting blog (I also love the theme/design), I don’t
    have time to go through it all at the minute but I have saved it
    and also added in your RSS feeds, so when I have time I will be back to
    read more, Please do keep up the awesome jo.

  38. Really Cheap Beats by Dre Says:

    some who found recovery act work in oak ridgeIn response to this problem, around a year ago Gilt introduced a more structured 2000term “product hierarchy” for merchandising specialists to index their inventory,/home.php?mod=space&uid=0, a component of which was to attach a “pretty name” or short label to each product category for frontend category navigation. Two thousand very specific categories were too granular for the number of products typically featured in a sale. In addition, categories w

  39. superman beats by dre for sale Says:

    hearing date set for trainer andersonSeveral examples Szatkowski cites to get his point across to audiences are shocking, so get a sitter for the children. This presentation is adultsonly. The session includes live, Internetconnected demonstrations of the salacious activities in chat rooms and examples of how some children behave online. Saturday at Oahu Cemetery Chapel. Aloha attire. Donations suggested to Friends of the Library of Hawaii, 690 Pohukaina St., Honolulu, HI 96813.. Glauben, da spe

  40. Says:

    I’m gone to inform my little brother, that he should also visit this web site on regular basis to take updated from most recent reports.

    Feel free to surf to my homepage – call of duty ghosts Hacks,,

  41. grosir baju anak tanah abang Says:

    I am genuinely grateful to the owner of this web site who
    has shared this impressive piece of writing at at this place.

  42. paket pulau pari Says:

    Everyone loves it when individuals come together and share thoughts.

    Great blog, stick with it!

  43. Anneliese Says:

    Today, while I was at work, my cousin stole my apple ipad
    and tested to see if it can survive a 25 foot drop, just so she can be a youtube sensation.
    My apple ipad is now destroyed and she has 83 views. I know this is
    totally off topic but I had to share it with

  44. {aruba|aruba weather| Says:

    It is the best time to make a few plans for the long run and it is time to be happy. I’ve read this submit and if I may I wish to counsel you few attention-grabbing things or advice. Maybe you can write next articles referring to this article. I want to learn more issues about it!

  45. Says:

    I am really impressed with your writing skills as well as with
    the layout on your weblog. Is this a paid theme or did you
    customize it yourself? Either way keep up the excellent quality writing, it’s rare to see a
    great blog like this one these days.

  46. Clash Of Clans Cheats For Iphone Free Says:

    There are young companies that offer competitive solutions.
    Video games have both their benefits and potential downfalls – but when used wisely and in moderation,
    they can be an excellent source of personal development and stress relief.
    They will work for you for a long time and with appropriate maintenance they can last lengthier than you think.

  47. Youtube to mp3 high quality Says:

    You really make it appear so easy with your presentation however I find this matter to be actually something that I elieve
    I might by no means understand. It sort of feels too complex and exrremely huge for me.
    I’m taking a look forward in your subsequent submit, I’ll
    try to get the dangle of it!

    Feel free to visit my website – Youtube to mp3 high quality

Leave a Reply