Manish
Manish

Reputation: 131

Usage of instanceof operator in JavaScript

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.

Upvotes: 0

Views: 62

Answers (2)

gurvinder372
gurvinder372

Reputation: 68363

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

Upvotes: 2

jojois74
jojois74

Reputation: 805

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

Upvotes: 1

Related Questions