Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do constructor functions return objects, but not primitives in JavaScript? [duplicate]

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

like image 223
BairDev Avatar asked Feb 29 '16 15:02

BairDev


1 Answers

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]]

  1. 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.
  2. If Type(result) is Object then return result.
  3. Return obj.

In fact, this is an invariant:

[[Construct]] ( )

  • The Type of the return value must be Object.
like image 76
Oriol Avatar answered Oct 15 '22 08:10

Oriol