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)?
Asked
Active
Viewed 2,089 times
9
-
See: http://stackoverflow.com/questions/1978049/what-values-can-a-constructor-return-to-avoid-returning-this/ – Christian C. Salvadó May 30 '10 at 14:28
2 Answers
22
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.

Amnon
- 7,652
- 2
- 26
- 34
2
The reason to use the new
operator is to ensure that this
inside the constructor refers to a new context, which supports:
this.functionName = function(){...};
, and to allow the use of the instanceof
operator:
function foo() {...}
var bar = new foo();
alert(bar instanceof foo);
Using return {...}
inside such a constructor negates both of these effects as this
will not be needed with such a pattern, and as instanceof
will return false
.

Sean Kinsey
- 37,689
- 7
- 52
- 71
-
Thanks for your response, i think this reveales a drawback of js constructors. – Tony May 30 '10 at 15:00