12

Suppose I have the following function:

var A = function() {
   var label = "hello";
   return {
      getLabel: function() { return label; }
   }
};

Is there any difference between:

var a = A();

and

var a = new A();

?

NB: I'm not asking here what is the 'new' keyword in JavaScript, but how it behaves in this particular example.

Community
  • 1
  • 1
sdabet
  • 18,360
  • 11
  • 89
  • 158
  • 3
    See http://stackoverflow.com/questions/1646698/what-is-the-new-keyword-in-javascript – pktangyue Feb 07 '13 at 09:09
  • please go through this http://stackoverflow.com/questions/1646698/what-is-the-new-keyword-in-javascript – ѕтƒ Feb 07 '13 at 09:10
  • Yes I've already read it. i was just wondering if there was any difference in this particular example – sdabet Feb 07 '13 at 09:11
  • @fmsf the question is about the given example, that's why I posted it despite the existence of http://stackoverflow.com/questions/1646698/what-is-the-new-keyword-in-javascript – sdabet Feb 07 '13 at 09:12
  • That whole ***new*** thing [is answered here][1] and [ also here][2]. [1]: http://stackoverflow.com/questions/1646698/what-is-the-new-keyword-in-javascript [2]: http://stackoverflow.com/questions/383402/is-javascript-s-new-keyword-considered-harmful – Ghoul Fool Feb 07 '13 at 09:12
  • 2
    @GhoulFool is it irrelevant to ask how the `new` thing applies in a specific context ? – sdabet Feb 07 '13 at 09:20

1 Answers1

8

In your particular instance, No, there is no difference.

Eitherw way, your function will return a self defined Object. By invoking a function with the new keyword, ECMAscript will automatically create a new object for you (alongside doing some magic with prototype and constructor properties), which you might access / write to via this within the function (-constructor).

Again, your return { } call in that function, will always return exactly that object reference.

jAndy
  • 231,737
  • 57
  • 305
  • 359