Rumah >hujung hadapan web >tutorial js >Apa yang Berlaku Apabila Pembina JavaScript Mengembalikan Nilai Bukan Objek?
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.
Atas ialah kandungan terperinci Apa yang Berlaku Apabila Pembina JavaScript Mengembalikan Nilai Bukan Objek?. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!