简体   繁体   中英

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.

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]] (ie 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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM