This is an old blog. My new blog is moved here.

JavaScript Class Constructor vs. Object Literal: Difference in Implementation and Inheritance

7/2/2009

There is a difference between object literal and what is called a "constructor" in JavaScript. For some reason a lot of people think that these two are interchangeable, but they are a totally different thing.

Here is an example:

    var objLit = {
    someProperty : "some value",
    someMethod : function(){
        console.log(this. someProperty)
        }
    }

This is most people refer to as object literal in JavaScript. It is an object that can be a accessed right away, with all its nodes, so when you want to call a method, it works like this:

objLit.someMethod();

On the other side you have a simple constructor, which might look like this:

    var myConst = function(){
        this.someOtherProperty = "some value";
        this.someOtherMethod = function(){
            console.log(this.someOtherProperty);
        }
    }

Obviously, if you want to call the inner method directly, it will not work, because it is not an object yet.

myConst. someOtherMethod();

First you have to create an "instance of a class:"

var myInst = new myConst();

Now you you have your public methods play with the public methods:

myInst. someOtherMethod();

Now there are more differences in implementing these two patterns. With a constructor, if you want to create a copy, you create a new instance:

var myInst = new myConst();

With an object literal, you can just simply make a copy of the object.

var newLitInstance = objLit;

And with this copy, you can do most of the things you would do with an instance, except inheritance. Yes, the prototype property does not work the way you are used to, so the following will not work:

objLit.prototype = new myConst();

Anyway, these things might be pretty simple, but I found that many people confuse these two quite a lot, so hopefully this clerification email will help to bring some light in the  foggy waters JavaScript wold.

Responses to The javascript class constructor vs. object literal: difference in implementation and inheritance

  1. Says:
    Monday, October 19, 2009 4:44 AM
    What about when I do this? will this still not work? afunction. someOtherMethod(); var afunction = new function()