Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between declaring javascript objects with var vs. with function?

I'm a confused newbie. I read in a tutorial that you create a javascript object like so:

function myObject() {
    this.myProperty = "a string";
    this.myMethod = function () {
        //Method code
    }
}

Then I read somewhere else that you create an object like so:

var myObject = {
    myProperty: "a string",
    myMethod : function () {
        //Method code
    }
}

What is the (non-subjective) difference between the two? Is there an official right way and a wrong way?

like image 386
randomable Avatar asked Oct 19 '10 14:10

randomable


2 Answers

Both declarations are correct but they have different semantics.

The first type of declaration allows you to create instances of your objects:

var t = new myObject();
// then use t
t.myProperty = "some value";

var otherT = new myObject();
otherT.myProperty = "some other value";

The second is almost like a static object:

myObject.myProperty = "some value";
like image 125
Mike Dinescu Avatar answered Sep 18 '22 02:09

Mike Dinescu


Here is a direct comparison...

function myObject() {

This declares the function when JavaScript is parsed...

var myObject = function () {

This declares the function at run time.

If you use the "var" method, your function must be declared before you use it... try this example.

myFunction(); // Works
myVarFunction(); // Boom

var myVarFunction = function () { alert("Hi"); };

function myFunction() { alert("Hi"); };

So why use the "var" method if you have to be more careful to use it? It is all to do with the scope... scoped functions are considered better.

UPDATE: And there are some great explanations here:

var functionName = function() {} vs function functionName() {}

like image 35
Fenton Avatar answered Sep 19 '22 02:09

Fenton