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)?
You do not specify a return type for a constructor. A return statement in the body of a constructor cannot have a return value.
The return statement ends function execution and specifies a value to be returned to the function caller.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With