JS Array.isArray

  node.js, question

See in MDNArray.isArray(Array.prototype) // true
But testing under Node found thatArray.prototype instanceof Array // false
Don’t understand what’s going on, ask the great god to answer.

MDN link:MDN Array.prototype

Because the judgment method is different

1. instanceof

  • First of all, the judgment method of instanceof is: whether each [[prototype]] pointer in the prototype chain on the left points to Array.prototype (that is, the prototype of the object on the right), and if so, returns true.

  • However, we know that [[prototype]] of Array.prototype points to object.prototype

    Array.prototype.__proto__ === Object.prototype;  // true
  • So, of course, using instanceof to judge is false

2. Array.isArray

  • According toStandard

  • There are three steps (open the refrigerator door … fog)

    • False if the parameter passed in is not Object

    • Returns true if the internal property [[Class]] is Array

    • False in all other cases

  • We all know that generally we get the [[Class]] attribute through the toString method. (In fact, this is the same judgment when there is no isArray method and simulation is needed.)

  • What will happen if we rewrite this method?

Object.prototype.toString = function() {
 return "[object Array]";
 Array.isArray({});  // false
  • It can be seen that isArray method is not affected.

  • So here I guess the js engine gets the value of [[Class]] directly during the comparison, not through the toString method. (If wrong, please point out _ (:Zje)

Ps added a little of the content of instanceof ~ =  ̄ Ω  ̄ = ~From here

function instance_of(L, R) {
 //L means left expression, r means right expression
 var O = R.prototype;  //Take the display prototype of R.
 L = L.__proto__;  //Take the implicit prototype of L.
 while (true) {
 if (L === null)
 return false;
 If (O === L)// emphasis here: returns true when o is strictly equal to l
 return true;
 L = L.__proto__;