Home > Web Front-end > JS Tutorial > Can Constructors Return Values Other Than 'this'?

Can Constructors Return Values Other Than 'this'?

Linda Hamilton
Release: 2024-11-14 13:01:02
Original
620 people have browsed it

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`".
Copy after login

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

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!

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