Return statement in JS constructors

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

+5
source share
2 answers

Usually returnjust exits the constructor. However, if the return value is an object, it is used as the value of the expression new.

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.

+17
source

The reason for using the operator newis to ensure that, thiswithin the constructor, it refers to a new context that supports:

this.functionName = function(){...};

instanceof:

function foo() {...}
var bar = new foo();
alert(bar instanceof foo);

return {...} , this , instanceof false.

+1

All Articles