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.

2
  • remove the return statement and then try Commented Mar 9, 2018 at 7:54
  • But your constructor returns a different object that is not an instance of the constructor in any sense. Commented Mar 9, 2018 at 7:54

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.