0

I've searched the site for this question and got the following answer:

function instance_of(V, F) {
  var O = F.prototype;
  V = V.__proto__;
  while (true) {
    if (V === null)
      return false;
    if (O === V)
      return true;
    V = V.__proto__;
  }
}

It's from https://stackoverflow.com/a/9220317/12974414.

But I tested the following code, found something weird:

console.log( (10).__proto__ === Number.prototype ) // true
console.log( instance_of(10, Number ) )            // true
console.log( 10 instanceof Number )                // false

function instance_of(V, F) {
  var O = F.prototype;
  V = V.__proto__;
  while (true) {
    if (V === null)
      return false;
    if (O === V)
      return true;
    V = V.__proto__;
  }
}

How to explain this and how does instanceof operator actually work in JS ?

MurphyChen
  • 57
  • 4
  • 1
    [Here's the spec](https://tc39.es/ecma262/multipage/ecmascript-language-expressions.html#sec-instanceofoperator) – phuzi Jul 06 '22 at 08:55
  • Also may be of interest https://stackoverflow.com/questions/2449254/what-is-the-instanceof-operator-in-javascript – phuzi Jul 06 '22 at 08:57
  • 1
    The function is correct when used *with objects*. It aims to clarify the behaviour in those cases, not add in excessive logic for handling primitives which would detract from the explanation. – VLAZ Jul 06 '22 at 09:05
  • 1
    `instanceof` works for objects, not for primitive values. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/instanceof – mbojko Jul 06 '22 at 09:06

1 Answers1

3

JavaScript has a feature called autoboxing which converts primitives to Objects when you try to access properties on them.

instanceof doesn't autobox and a primitive number is not an instance of the Number class.

You can see, in the specification:

  1. If Type(O) is not Object, return false.
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335