JavaScript, jquery

difference between object literal and what is called a “constructor” in JavaScript


 

reference:http://www.davidpirek.com/blog.aspx?n=JavaScript-Class-Constructor-vs.-Object-Literal:-Difference-in-Implementation-and-Inheritance

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.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s