跳至正文

JavaScript中 instanceof 的实现原理

一 定义

标准的MDN定义:用于检测构造函数的 prototype 属性是否出现在某个实例对象的原型链上。
用简单通俗的话来说就是,判断左侧是否为右侧的实例化对象。

二 使用方法

使用格式为:a instanceof b。其中,左侧 a 为对象,右侧 b 必须为函数类型。

示例代码如下

'abc' instanceof String; // false,因为'abc'为简单字符串,不是通过String构造函数创建出来的
new String('abc') instanceof String; // true

100 instanceof Number; // false
new Number(100) instanceof Number; // true

[1,2] instanceof Array; // true

function f1() {};
f1 instanceof Function; // true

三 实现原理

检测a的原型链(__proto__)上是否有b的显式原型(prototype),有则返回true,否则false。

实现代码如下。

// a表示左侧表达式,b表示右侧表达式
function my_instanceof(a, b) {
    if (typeof a !== 'object' && typeof a !== 'function') {
        return false;
    }
    let a1 = a.__proto__;  // 取 a 的隐式原型
    const b1 = b.prototype;   // 取 b 的显式原型
    while (true) {
        if (a1 === null) {
            return false;
        } 
        if (a1 === b1) { // 当 a 显式原型严格等于 b 隐式原型时,返回true
             return true;  
        }
        a1 = a1.__proto__;
    }
}

再次运行上面的测试示例,结果一样。

my_instanceof('abc', String); // false
my_instanceof(new String('abc'), String); // true

my_instanceof(100, Number); // false
my_instanceof(new Number(100), Number); // true

my_instanceof([1,2], Array); // true

function f1() {};
my_instanceof(f1, Function); // true
标签:

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注