当前位置:网站首页>How exactly does instanceof judge the reference data type!

How exactly does instanceof judge the reference data type!

2022-06-11 06:28:00 Saucey_ six

Procrastination .... It has to be cured !( Just began to sum up the problems encountered in the autumn moves )


The problem is that :

Judge JavaScript Methods of data type :( Okay , Just write it down )

  1. The most common :typeof Judge , But its drawback is , The types returned are all in string form
  1. typeof null ===object,
  2. It cannot judge Array type , The determined array type is Object.
  1. When the object type is known :instanceof

that , So the question comes ,instanceof How to judge .

  1. Based on the constructor Judge :constructor
  1. constructor Property returns an array that creates this object , References to functions .
  1. Object.prototype.toString.call()==='[object Array]' To judge . Universal , But it's troublesome .

instanceof How to judge the reference type .

The first reaction is to inherit , But I seem to think too much .
Look at a piece of code :

function A(){}
let a = new A()
console.log(a instanceof A)//true

Obviously instanceof Is to judge whether an instance belongs to a certain type
Of course it's clear ,instanceof You can determine whether an instance belongs to its parent type in the inheritance relationship .

function instance_of(L, R) {
    var O = R.prototype;// R The display prototype of 
    L = L.__proto__;// L The implicit prototype of 
    while (true) {
        /* Object.prototype.__proto__ === null*/
        /* __proto__  Point to its prototype object  */
        if (L === null) {
            return false
        }
        if (L === O) {
            return true
        }
        L = L.__proto__;
    }
}

all JavaScript Object has proto attribute , But only Object.prototype.proto by null, The premise is that it is not Firefox perhaps Chrome I have modified this property . This property points to its prototype object .

ok, About the same , We continue .

Push : Object instanceof Object

ObjectL = Object, ObjectR = Object;
O = ObjectR.prototype = Object.prototype
L = ObjectL.__proto__ = Function.prototype
//  For the first time 
O !== L
L = Function.prototype.__proto__ = Object.prototype//  Loop search  L  Is there any more  __proto__
//  Second judgment 
O === L//  return  true

Reference article

原网站

版权声明
本文为[Saucey_ six]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/162/202206110623220562.html