Home >Web Front-end >JS Tutorial >Can a JavaScript Constructor Return Values Other Than the Constructed Object?

Can a JavaScript Constructor Return Values Other Than the Constructed Object?

DDD
DDDOriginal
2024-11-10 21:43:02605browse

Can a JavaScript Constructor Return Values Other Than the Constructed Object?

Constructor Return Values and the [Instanceof] Operator

In JavaScript, a constructor function can return values other than the constructed object. Understanding these circumstances is crucial for avoiding runtime errors like unexpected results from the instanceof operator.

The ECMAScript 3rd Edition Specification defines the [[Construct]] property, which governs constructor behavior. According to the specification:

  • Step 7: If the return value from the constructor function (Result(6)) is not an Object type, return Result(6).
  • Step 8: Otherwise, return the newly constructed object (Result(1)).

Therefore, a constructor can return non-primitive values (like functions or arrays) to prevent the instanceof operator from returning true.

For example:

function Foo() {
  return [];
}

const foo = new Foo();
console.log(foo instanceof Foo);  // false

Since the constructor returns an array (non-Object), the instanceof check fails. Conversely, returning a primitive value (like null or undefined) would still return true.

In summary, the values returned by a constructor can affect the instanceof result. By understanding the conditions outlined in the [[Construct]] property, developers can prevent unexpected behavior and ensure accurate class inheritance checking.

The above is the detailed content of Can a JavaScript Constructor Return Values Other Than the Constructed Object?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn