Home > Web Front-end > JS Tutorial > What Happens When a JavaScript Constructor Returns a Non-Object Value?

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

Patricia Arquette
Release: 2024-11-13 10:16:02
Original
304 people have browsed it

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;
}
Copy after login

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.

The above is the detailed content of What Happens When a JavaScript Constructor Returns a Non-Object Value?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template