Rumah >hujung hadapan web >tutorial js >Apa yang Berlaku Apabila Pembina JavaScript Mengembalikan Nilai Bukan Objek?

Apa yang Berlaku Apabila Pembina JavaScript Mengembalikan Nilai Bukan Objek?

Patricia Arquette
Patricia Arquetteasal
2024-11-13 10:16:02314semak imbas

What Happens When a JavaScript Constructor Returns a Non-Object Value?

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:

  • A new object is created, and Foo's prototype is set as its prototype.
  • Foo.call(newObj, args) is invoked (in this case, there are no arguments).
  • Foo returns 1.
  • Since 1 is not an Object, step 7 is executed, and 1 is returned from the constructor.

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!

Kenyataan:
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn