I'm 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've read) :
When the
constructor
returns an object, thenew
operator will yield the returned object
So since f
is a function
- the new
operator will yield the returned object which is f
in this case
So : new f() === f
Hence : f instanceof f
//false.
Question :
I 'm searching for this behaviour description in the docs , but couldn't find it.
I only found partial answer in mdn :
However - looking at the docs (which is what I really after) :
All it say is :
It doesn't mention the cases where the constructor
return object or not
( i'm sure i'm missing it)
Question: Where does in the docs that behavior is explained ?
nb ,
I know that constructor function should not (generally) return anything , this question is for knowledge.
nb2 :
example for this behaviour :
var z = {a: 2};
function g() { return z; }
var x = new g();
x === z; //true
Here, x is actually equal to z, down to the identity!
That's because this behavior is a property of the internal [[Construct]]
method, not new
:
1. Let
obj
be a newly created native ECMAScript object.
[...]
8. Letresult
be the result of calling the[[Call]]
internal property ofF
, providingobj
as the this value and providing the argument list passed into[[Construct]]
asargs
.
9. IfType(result)
isObject
then returnresult
.
10. Returnobj
.
F
is the function that is called via new
(f
in your case). Since f
returns an object (step 8), it is returned (step 9). If it was not an object, the object in step 1 would be returned (step 10).
new
simply returns what [[Construct]]
returns:
5. Return the result of calling the
[[Construct]]
internal method [...]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With