Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

instanceof in case of Function in JavaScript

Tags:

javascript

The first question I was asked in the interview, and to be honest I saw myself really confused and shown the door,

Consider the snippets:

Case a:

    var sayHello = new Function("alert('Hello there');");
    alert(sayHello instanceof Function);            // true 
    alert(sayHello instanceof Object);              // true, since every 
                                                    // object inherits from Object

Case b:

    var myFunction = function(){

    }

    var ins = new myFunction();              
    alert(ins instanceof myFunction);        // ofcourse, true
    alert(myFunction instanceof Function);   // true

    alert(ins instanceof Function);          // false, Why is this not true?

As per my understanding, Function must be in the prototypical chain of ins?

ins <-- myFunction <-- Function <-- Object
like image 318
Farhan Shirgill Ansari Avatar asked Sep 03 '15 06:09

Farhan Shirgill Ansari


2 Answers

You seem to misinterpret the new here in Javascript.

The

new myFunction()

doesn't create a new instance of the function. Rather it creates a new object which inherits from myFunction.prototype and calls myFunction, passing the object as this to the function.

Thus, you haven't really created a new instance of the function, your ins is not a function. You can easily verify it by trying to pretend it is:

var myFunction = function(){

}

var ins = new myFunction(); 

ins(); <-- error, ins is not a function

Since it is not a function, why would you expect the Function to be in its prototype chain?

like image 181
Wiktor Zychla Avatar answered Sep 21 '22 23:09

Wiktor Zychla


So, you have it close, but not quite. The prototypal chain is actually as follows:

ins <-- myFunction.prototype <-- Object

As you can see, the ins object inherits from the particular function prototype, and not from Function directly.

So, in essence ins is not an instance of a myFunction, so much as an instance of myFunction.prototype.

This can be more clearly be shown, by the fact that when you add functions to myFunction.prototype, they are attached to the instance of the object once it has been created.

For a great source of information on exactly what is happening, check out https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/new This explains the behaviour fully.

like image 21
major-mann Avatar answered Sep 20 '22 23:09

major-mann