0

I started learning JavaScript and have below question:

var f = function foo() {}
Console.log(f.__proto__ === Function.prototype) //true 
Console.log(f.__proto__ instance of Function) //false

Why 3rd statement using instanceof returns false. My understanding is RHS of instance consults prototype of passed class and then match it in object or its proto. Please let me know what I am missing here? referred this for implementation of instance-of.

Narendra Jadhav
  • 10,052
  • 15
  • 33
  • 44

1 Answers1

0

referred this for implementation of instance-of

Well, that's simply a wrong implementation. The instanceof operator does not match the object itself, only its prototypes, against the .prototype of the constructor. Your

x instanceof Function

is equivalent to

Function.prototype.isPrototypeOf(x)

which for f.__proto__ (i.e. Function.prototype) does not hold - it is not the prototype of itself.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • Thanks, i have no idea about isprototypeof. will read about that. IN this case f.__proto__ ->Function.prototype; instanceof finds prototype property of RHS i.e. Function.prototype and then tries to find a match. Isn't that correct? If not, is there a way to find implemented code of instanceof. –  Apr 21 '18 at 09:25
  • Yes, it tries to find `Function.prototype` (the LHS) in the prototype chain of the `.prototype` of `Function` (the RHS). But it is not in the chain, it is the start of the chain. – Bergi Apr 21 '18 at 10:21
  • You can read about `isPrototypeOf` [here](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/isPrototypeOf) – Bergi Apr 21 '18 at 10:22