Javascript `new` keyword in the returned array of functions

I experimented with the new keyword and I cannot find an explanation for this behavior. Let them say that we have a function that returns an integer:

(In firebug)

 >>> function x() { return 2; } >>> x() 2 >>> new x() x { } 

But if the function returns an array:

 >>> function y() { return [2]; } >>> y() [2] >>> new y() [2] 

Why is this?

+6
source share
2 answers

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").

+16
source

Since the array is an object, but 2 not.

If you call a function with the new keyword, it should return an object. If you do not do this explicitly, it will automatically return this (which is an empty object that inherits from funcName.prototype) .

+5
source

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


All Articles