I'm trying to understand JavaScript's (or at least V8's) behaviour regarding constructor functions.
I know, JavaScript constructor functions should never return anything (so: undefined
).
But consider this JavaScript:
function Thing() {
return '';
}
var t = new Thing();
console.log(t, typeof t); // => Thing {} "object"
Now, if you do this:
function Thing() {
return { hi: '' };
}
var t = new Thing();
console.log(t, typeof t); // => Object {hi: ""} "object"
And even:
function Thing() {
this.a = 'a';
return { hi: '' };
}
var t = new Thing();
console.log(t, typeof t); // => Object {hi: ""} "object"
So, why does a constructor function in JavaScript return an object, but not a primitive, if you write this kind of code?
This behaviour is also mentioned in this SO answer, but not explained. I've also scrolled over The new Operator part of the ECMAScript specification, and its Construct snipped, but this was not enlightening.
Any hints or knowledge (in plain English, please)?
That's because, by definition, the purpose of constructors is producing objects, not primitives:
4.3.4 constructor
function object that creates and initialises objects
Therefore, the [[Construct]] internal method (called via the new
operator), checks the type of the value returned by [[Call]]:
13.2.2 [[Construct]]
- Let result be the result of calling the [[Call]] internal property of F, providing obj as the this value and providing the argument list passed into [[Construct]] as args.
- If Type(result) is Object then return result.
- Return obj.
In fact, this is an invariant:
[[Construct]] ( )
- The Type of the return value must be Object.
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