views:

77

answers:

3

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?

A: 

The difference is that with function, you can reuse the object like a template, and you can test if an object is of a specific "type".

And of course the biggest difference is that a function has code that is executed when the object is initialized, unlike the object.

But you are right to wonder, they are indeed quite similar.

wildpeaks
+3  A: 

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";
Miky Dinescu
i would rather call the second one a *singleton* without a constructor.
galambalazs
Thanks for comparing it to a static object. That's a great way to explain it.
randomable
+2  A: 

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:

http://stackoverflow.com/questions/336859/javascript-var-functionname-function-vs-function-functionname

Sohnee
Thanks for that link! One answer said that var was scoped, but another answer corrected it, saying they are both scoped. I tested it out, and it appears to me that both var and function scope in the same way. Or is there some other condition where they don't?
randomable
@randomable - yes, scope in this scenario seems to cause confusion... I may be another victim. Check this out : https://developer.mozilla.org/en/JavaScript/Reference/Functions_and_function_scope
Sohnee