Home > Web Front-end > JS Tutorial > body text

Why Does a Constructor Function Sometimes Return a Non-this Value?

Susan Sarandon
Release: 2024-11-11 12:53:02
Original
1021 people have browsed it

Why Does a Constructor Function Sometimes Return a Non-this Value?

The Curious Case of Non-this Returns in Constructor Functions

When invoking a constructor function with the new keyword, it's generally assumed that the function will return the newly created object. However, under specific circumstances, a non-this value can be returned instead.

In JavaScript, the exact condition that governs this behavior is defined in the ECMAScript specification's internal [[Construct]] property for function objects. When called, this property performs the following steps:

  1. Creates a new object.
  2. Sets its [[Class]] property as "Object".
  3. Retrieves the value of the prototype property from the constructor function.
    4-5. Sets the [[Prototype]] property of the new object to the prototype value (if it's an object) or the original Object prototype object otherwise.
  4. Invokes the [[Call]] property of the constructor function, using the new object as this, passing the constructor arguments as its arguments.
    7-8. Crucial Step: Returns the new object if Type(Result(6)) is not an Object, or returns Result(1) (i.e., the new object created in step 1) otherwise.

Hence, the value returned by the constructor function will determine whether the newly created object is returned or not:

  • If the returned value is a non-object primitive, the new object will be returned.
  • If the returned value is any object, this will be returned instead.

To test if the newly created object is truly different from the one returned by the constructor, one can check: (new Foo() instanceof Foo) === false.

The above is the detailed content of Why Does a Constructor Function Sometimes Return a Non-this 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