Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return Statement in JS Constructors

What is the effect of a return statement in the body of JavaScript function when it's used as a constructor for a new object(with 'new' keyword)?

like image 423
Tony Avatar asked May 30 '10 14:05

Tony


People also ask

Can we use return statement in constructor?

You do not specify a return type for a constructor. A return statement in the body of a constructor cannot have a return value.

What is return () in JavaScript?

The return statement ends function execution and specifies a value to be returned to the function caller.

What does the constructor function return?

No, constructor does not return any value. While declaring a constructor you will not have anything like return type. In general, Constructor is implicitly called at the time of instantiation. And it is not a method, its sole purpose is to initialize the instance variables.

What is return type of constructor in JavaScript?

The constructor property returns a reference to the Object constructor function that created the instance object. Note that the value of this property is a reference to the function itself, not a string containing the function's name. Note: This is a property of JavaScript objects.


1 Answers

Usually return simply exits the constructor. However, if the returned value is an Object, it is used as the new expression's value.

Consider:

function f() {
   this.x = 1;
   return;
}
alert((new f()).x);

displays 1, but

function f() {
   this.x = 1;
   return { x: 2};
}
alert((new f()).x);

displays 2.

like image 111
Amnon Avatar answered Oct 06 '22 08:10

Amnon