I am trying to understand the behavior of JavaScript (or at least V8) regarding constructor functions.
I know that JavaScript constructor functions should never return anything (like this: undefined
).
But consider this JavaScript:
function Thing() { return ''; } var t = new Thing(); console.log(t, typeof t);
Now if you do this:
function Thing() { return { hi: '' }; } var t = new Thing(); console.log(t, typeof t);
And even:
function Thing() { this.a = 'a'; return { hi: '' }; } var t = new Thing(); console.log(t, typeof t);
So, why is the constructor function in JavaScript returning an object, but not primitive, if you write such code?
This behavior is also mentioned in this SO answer , but not explained. I also scrolled the new statement in the ECMAScript and Construct specs, but that was not clear.
Any hints or knowledge (in plain English, please)?
source share