Why do constructor functions return objects but not primitives in JavaScript?

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); // => 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 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)?

+5
source share
1 answer

This is because, by definition, the goal of designers is to create objects, not primitives:

constructor 4.3.4

function object that creates and initializes objects

Therefore, the [[Construct]] internal method (called through new ) checks the type of value returned by [[Call]] :

13.2.2 [[Construct]]

  1. Let the result be called by the internal [[Call]] property of F, providing obj as the value of this and providing a list of arguments passed to [[Construct]] as args.
  2. If Type (result) is an object, then returns the result.
  3. Return obj.

Actually this is invariant :

[[Construct]] ()

  • The return type must be an Object.
+4
source

Source: https://habr.com/ru/post/1244127/


All Articles