The new operator has an interesting behavior: it returns the object created by the operator if the constructor function does not return another object. Any non-returning value of the constructor function is ignored, so when you return 2 , you do not see this.
This is what happens when you say new x() :
- The interpreter creates a new empty object.
- It installs a prototype object under
x.prototype . - It calls
x with this set to the new object. - In the normal case,
x does not return anything, and the result of the new expression is the new object created in step 1. But , if x returns a non- null reference to the object, then this reference to the object is the result of the new expression, not the object created on step 1. Any other return value ( null , primitive numbers, primitive strings, undefined , etc.) is ignored; it must be a reference to the null object in order to take precedence over the created new object.
This special call to object references by the new operator allows you to substitute another object for the new created. This may be convenient in some limited situations, but in most cases a function intended for use with new (called a constructor function) should not return anything at all.
For some easy reading (hah!) This is covered in Section 13.2.2 ("[[[Construct]]") specification ( HTML ; PDF ) referenced in Section 11.2.2 ("The new operator").
source share