0

Can someone explain why does this code snippet returns result as "false"

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

As per my understanding instanceof checks the current object and returns true if the object is of the specified object type.

So "new f()" should act as a current object and it is an instance of type f. Consequently result should be true.

Manish
  • 131
  • 5

2 Answers2

2

new function() does much more than invoking the constructor and returning its output.

It creates a new object. The type of this object is simply object.

It sets this new object's internal, inaccessible, [[prototype]] (i.e. proto) property to be the constructor function's external, accessible, prototype object (every function object automatically has a prototype property).

It makes the this variable point to the newly created object.

It executes the constructor function, using the newly created object whenever this is mentioned.

It returns the newly created object, unless the constructor function returns a non-null object reference. In this case, that object reference is returned instead.

However, if the function's constructor already returns a value, then output of new function() is same as function()

function f1(){ return f1 }
f1() == new f1() //returns true

Without return statement in constructor

function f1(){ }
f1() == new f1() //returns false
gurvinder372
  • 61,170
  • 7
  • 61
  • 75
1

Remove the return f. New will give you an object unless you return something else, in this case the function f.

jojois74
  • 715
  • 4
  • 10