Constructor function returning object - specification of documentation?

I am trying to find in the docs / understand this behavior for the following code:

I saw this piece of code here :

function f(){ return f; } new f() instanceof f; //false 

This is because (from what I read ):

When the constructor object returns an object, the new operator will give the returned object

Since f is a function , the new operator returns a return object, which in this case is f

So: new f() === f

Therefore: f instanceof f // false.

Question:

I searched for this description of behavior in documents, but could not find it.

I found only a partial answer in mdn :

enter image description here

However - looking at the docs (this is what I really am after):

All he says is:

enter image description here

It does not mention cases where constructor return object or not (I'm sure it is missing)

Question: Where do the documents explain this behavior?

nb

I know that the constructor function should not (in general) return anything, this question is for knowledge.

nb2:

an example for this behavior:

 var z = {a: 2}; function g() { return z; } var x = new g(); x === z; //true 

Here x is actually equal to z, right up to the identity!

+7
javascript
source share
3 answers

This is because this behavior is a property of the [[Construct]] internal method , and not new :

1. Let obj be the newly created native ECMAScript object.
[...]
8. Let result be the result of calling the [[Call]] internal property of F , providing obj as that value and providing a list of arguments passed to [[Construct]] as args .
9. If Type(result) is Object , then return result .
10. Return obj .

F is a function that is called through new ( F in your case). Since F returns the object (step 8), it returns (step 9). If it was not an object, the object in step 1 will be returned (step 10).

new just returns what [[Construct]] returns:

5. Returns the result of calling the internal method [[Construct]] [...]

+6
source share

What you are looking for is found here . The NewExpression documentation you mentioned above states that it

returns the result of calling the internal method [[Construct]]

The specification for the [[Construct]] method is what you need.

+3
source share

Page 100 here :

... 8 Let the result be called by the internal [[Call]] property of F, providing obj as this value and providing the argument list passed to [[Construct]] as args.

9 If Type (result) - Object, then returns the result.

10 Return obj.

+2
source share

All Articles