Home > Article > Web Front-end > 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:
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!