How exactly does Javascript instanceof work? Is it slow style?

前端 未结 3 506
面向向阳花
面向向阳花 2021-01-04 19:24

How does the performance of instanceof fair for \"huge libraries\"?

Does it travel up the prototype chain one by one, similar to this?

3条回答
  •  耶瑟儿~
    2021-01-04 20:04

    According to what Felix Kling quoted, all that instanceof does (excluding the error checks) is to check whether the prototype property(which has to be an object) of the Function can be found somewhere down the prototype chain

    person instanceof Object
    // ROUGHTLY does
    return (
         person.__proto__==Object.prototype
      || person.__proto__.__proto__==Object.prototype
      || ... );
    

    Here's some pseudocode:

    person instanceof Person
    //ROUGHTLY equals
    person.instanceOf(Person)
    
    person.instanceOf = function(Person) {
        if(typeof Person!='object') throw new TypeError;
        if(!([[HasInstance]] in Person)) throw new TypeError;
        return Person.[[HasInstance]](this /* person */)
    }
    
    
    Person.[[HasInstance]] = function(V) {
        if(typeof V!='object') return false;
        var O = this.prototype;
        if(typeof O!='object') throw new TypeError;
        while(true) {
            V = V.__proto__; // [[prototype]] (hidden) property
            if(V==null) return false;
            if(V==O) return true;
        }
    }
    

提交回复
热议问题