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
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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With