Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript 'new' with function returning self-defined object [duplicate]

Tags:

javascript

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.

like image 266
sdabet Avatar asked Feb 07 '13 09:02

sdabet


People also ask

What happens when you call a function with new keyword?

New keyword in JavaScript is used to create an instance of an object that has a constructor function. On calling the constructor function with 'new' operator, the following actions are taken: A new empty object is created.

What does JavaScript return to you if you try to access an object's property that doesn't exist?

If I tried to access a property name in an object that does not exist, then I would get undefined. For example, if I tried developer. age then the return value would be undefined because the developer object does not have that property name. We can check if a property exists in the object by checking if property !==

What property of JavaScript functions can store shared behavior for instances created with new?

The prototype property of a Javascript object is shared among all the instances/copies of the object and can be used to store shared data/state.


1 Answers

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.

like image 158
jAndy Avatar answered Oct 21 '22 03:10

jAndy