Understanding Constructor Return Values in JavaScript
In JavaScript, constructors are invoked using the new keyword to create new objects. While the constructor typically returns this, certain conditions can result in different values being returned.
Circumstances for Returning Non-This Values
The behavior is defined by the internal [[Construct]] property used by the new operator. According to the ECMA-262 3rd Edition Specification:
Step 7: If the type of the value returned from the constructor function (Result(6)) is not an Object, return Result(6).
Step 8: Otherwise, return Result(1) (the new object).
Example:
Consider the following constructor:
function Foo() { return 1; }
When invoked with new, the following steps occur:
Thus, (new Foo() instanceof Foo) === false because Foo returned a number, not an object.
Conclusion:
When a constructor returns a non-object value (e.g., a primitive, null, undefined), this is not returned and the constructor function's returned value is returned instead.
Das obige ist der detaillierte Inhalt vonWas passiert, wenn ein JavaScript-Konstruktor einen Nicht-Objektwert zurückgibt?. Für weitere Informationen folgen Sie bitte anderen verwandten Artikeln auf der PHP chinesischen Website!