Home  >  Article  >  Web Front-end  >  Can Constructors Return Values Other Than "this"?

Can Constructors Return Values Other Than "this"?

Linda Hamilton
Linda HamiltonOriginal
2024-11-14 13:01:02549browse

Can Constructors Return Values Other Than

Return Values for Constructors That Bypass the "this" Reference

When invoking a constructor using the new keyword, the default behavior is for the constructor to return the newly created object (referred to as "this"). However, there are specific circumstances where a constructor can return a different value, effectively preventing the assignment of "this" to the newly created object.

According to the ECMAScript specification, step 8 of the [[Construct]] internal property defines the return behavior as follows:

If the type of the value returned by the constructor function (Result(6)) is not an Object:

- The value returned by the constructor will be returned instead of "`this`".

Therefore, to return a value other than "this" from a constructor:

  1. Return a non-object primitive (such as a string, number, or boolean): If the returned value is a primitive, it will not be interpreted as an object, and thus the new object will not be returned.
  2. Return a custom object or a non-null value with a type other than Object: This can be achieved using the Object.create() method or by assigning a different prototype to the created object.

Example:

function Foo() {
    return { name: "sample" };
}

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

In this case, since the Foo constructor returns an object that is not an instance of the Foo constructor, (new Foo() instanceof Foo) will evaluate to false.

The above is the detailed content of Can Constructors Return Values Other Than "this"?. 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