Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Constructor function returning object - documentation clarification?

Tags:

javascript

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, the new 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 :

enter image description here

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

All it say is :

enter image description here

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!

like image 997
Royi Namir Avatar asked Mar 20 '14 15:03

Royi Namir


1 Answers

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. Let result be the result of calling the [[Call]] internal property of F, providing obj as the this value and providing the argument list passed into [[Construct]] as args.
9. If Type(result) is Object then return result.
10. Return obj.

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 [...]

like image 114
Felix Kling Avatar answered Oct 20 '22 00:10

Felix Kling