Home >Web Front-end >JS Tutorial >Can Constructors Return Values Other Than 'this'?
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:
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!