-2

What is the difference between these 2 types of structures

var bar = { 
    something : value,
    execute : function() { /* Whatever */ }
}

function foo() {    
    this.something = value;
    this.execute = function() { /* Whatever */ };
}

My reasoning is that bar is a static object, and foo is a regular object that has to be created calling the new constructor

Is that correct ? Or not really

Matt Burland
  • 42,488
  • 16
  • 89
  • 156
sahmed24
  • 318
  • 2
  • 3
  • 13
  • 2
    It's correct as long as you see it only as a metaphor to compare with other languages. – Denys Séguret Mar 22 '13 at 16:46
  • yes, that looks right – Arun P Johny Mar 22 '13 at 16:46
  • 1
    @AaronKurtzhals I'm sure the present question is a duplicate, we seem to see it multiple times a day, but probably not of the question you link to. – Denys Séguret Mar 22 '13 at 16:48
  • possible duplicate of [What is the difference between declaring javascript objects with var vs. with function?](http://stackoverflow.com/questions/3969689/what-is-the-difference-between-declaring-javascript-objects-with-var-vs-with-fu) – Denys Séguret Mar 22 '13 at 16:51
  • Please clarify your question. There is no such thing in javascript as a static object. Are you asking about the finer points of the difference between an object and a function? Are you asking about the difference between using object literal syntax `{}` and `new`? – Aaron Kurtzhals Mar 22 '13 at 16:58

1 Answers1

1

I assume you mean what's the difference between bar (as you declared it) and

var bar2 = new foo();

There's not a lot of difference between bar and bar2, other than that the prototype for bar will always be the prototype property of Object (as if you had written var bar = new Object(); bar.something = value; bar.execute = function() {...}), while the prototype for bar2 will be whatever is assigned to the prototype property of foo (or the prototype property of Object by default).

Other than the issue of prototypes, writing a constructor function is mostly a matter of convenience.

Note that with the constructor approach, you can use the prototype to advantage:

function foo() {    
    this.something = value;
}

foo.prototype.execute = function() { /* Whatever */ };

Then all instances of foo share the same execute function. This is much more space efficient than having a new function object for each foo object. (Of course, if you're only creating one of these, there's not much advantage.)

Ted Hopp
  • 222,293
  • 47
  • 371
  • 489