From Mozilla JavaScript Reference:
The object returned by the constructor function becomes the result of the whole new expression. If the constructor function doesn't explicitly return an object, the object created in step 1 is used instead. (Normally constructors don't return a value, but they can choose to do so if they want to override the normal object creation process.)
In simpler words, this is how constructor calling works in JavaScript, i.e. if you return nothing or a primitive type (like plain string
or numbers
) or this, then they will be ignored and this
will eventually be returned. However if you return an object or function from the constructor, that object will be returned with new
.
I borrowed the following code from this blog post, which may be helpful here.
// Undefined return value.
function A() {
return;
}
// Reference to instance.
function B() {
return (this);
}
// String return value.
function C() {
return ("string");
}
// Number retun value.
function D() {
return (123);
}
// New object return value.
function E() {
return ({
foo: "bar"
});
}
// New array return value.
function F() {
return (["foo", "bar"]);
}
// New instantiation return value.
function G() {
return (new A());
}
// Native "object" return value -- this one would be the same
// for Number, Boolean, and String.
function H() {
return (new Number(123));
}
// -------------------------------------------------- //
// -------------------------------------------------- //
// See what reference we have as a result of instantiation.
console.log(new A());
console.log(new B());
console.log(new C());
console.log(new D());
console.log(new E());
console.log(new F());
console.log(new G());
console.log(new H());
this returns
A {}
B {}
C {}
D {}
Object { foo="bar"}
["foo", "bar"]
A {}
Number {}