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)?