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 a class 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;
}

function getAppleInfo() {
    return this.color + ' ' + this.type + ' apple';
}

To instantiate an object of the Apple class, 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 same class, 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.

2. Using JSON

JSON stands for JavaScript Object Notation; it simply uses the short way of defining objects and arrays in JavaScript. To create an empty object using JSON 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 using the JSON you can define a class, while at the same time creating an instance (object) of that class. Such a class/object is also called "singleton" which means that you can have only one single instance of this class at any time, you cannot create more objects of the same class. Here's the same class described in the previous examples, but using JSON 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());

3. Singleton using a function

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 class. 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());

Summary

You saw three (plus one) ways of defining a class and instantiating an object of this class in JavaScript. Looking forward to start coding using the new knowledge? Happy JavaScript-ing!

Bookmark and Share

Somewhat related posts

21 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. neon tabela Says:

    many open issues, the information super, thanks for sharing.

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

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

Leave a Reply