5

If there is a constructor like

function a() {}

then

(new a) instanceof a === true

But on the other hand,

function a() { return {} }

results in

(new a) instanceof a === false

So what I was thinking is that

function a() { return 123 }

would result in the same thing. However, when returning a Number,

(new a) instanceof a === true

How is this possible? Why can't I make a constructor return something else than an Object?

(I do know making a constructor returning a Number is rather useless but I would like to understand the 'why' of this behaviour)

pimvdb
  • 151,816
  • 78
  • 307
  • 352
  • A constructor isn't meant to return an object – qwertymk Jul 21 '11 at 11:54
  • 1
    Nitpickery: You can certainly return a `Number`, but not a `number`: `function a() { return new Number(123); }`. The result can even be used as a number (`a() + 1 === 124`), it just won't compare `===` to a true number with its value. – Kevin Reid Jul 21 '11 at 13:58
  • 1
    @Kevin Reid: I see. I guess that's because `Number` is an Object whilst `number` is a primitive. (is that correct?) – pimvdb Jul 21 '11 at 14:01
  • pimvdb: Yes. Usually it is good to avoid the value-wrapper objects as they can cause confusion due to their slightly different semantics. The main place you find them is that a method called on a number has `this instanceof Number`. – Kevin Reid Jul 21 '11 at 15:24
  • Possible duplicate of [What is returned from a constructor?](https://stackoverflow.com/questions/3350215/what-is-returned-from-a-constructor) – Liam Jun 28 '17 at 14:29

1 Answers1

7

According to the spec: If calling the constructor returns an object, then this object is the result of the new-expression. If the constructor doesn't return an object (but undefined or some other primitive value), the result is the newly created object.

If primitives were allowed, then all constructors would have to explicitly return something (typically "this"), otherwise the result would be undefined (because the result of a function without a return is undefined). That would be a needless hassle.

Additionally, it makes sense that new can be relied on to always return an object.

JacquesB
  • 41,662
  • 13
  • 71
  • 86