您当前的位置:首页 > 网站建设 > javascript
| php | asp | css | H5 | javascript | Mysql | Dreamweaver | Delphi | 网站维护 | 帝国cms | React | 考试系统 | ajax | jQuery | 小程序 |

JavaScript 手动实现instanceof的方法

51自学网 2022-02-21 13:38:39
  javascript

1. instanceof的用法

instanceof运算符用于检测构造函数的prototype属性是否出现在某个实例对象原型链上。

function Person() {}function Person2() {}const usr = new Person();console.log(usr instanceof Person); // trueconsole.log(usr instanceof Object); // trueconsole.log(usr instanceof Person2); // false

如上代码,定义了两个构造函数,PersonPerson2,又实用new操作创建了一个Person的实例对象usr

实用instanceof操作符,分别检验构造函数prototype属性是否在usr这个实例的原型链上。

当然,结果显示,PersonObjectprototype属性在usr的原型链上。usr不是Person2的实例,故Person2prototype属性不在usr的原型链上。

2. 实现instanceof

明白了instanceof的功能和原理后,可以自己实现一个instanceof同样功能的函数:

function myInstanceof(obj, constructor) {    // obj的隐式原型    let implicitPrototype = obj?.__proto__;    // 构造函数的原型    const displayPrototype = constructor.prototype;    // 遍历原型链    while (implicitPrototype) {        // 找到,返回true        if (implicitPrototype === displayPrototype) return true;        implicitPrototype = implicitPrototype.__proto__;    }    // 遍历结束还没找到,返回false    return false;}

myInstanceof函数接收两个参数:实例对象obj和构造函数constructor

首先拿到实例对象的隐式原型:obj.__proto__,构造函数的原型对象constructor.prototype

接着,就可以通过不断得到上一级的隐式原型

implicitPrototype = implicitPrototype.__proto__;

来遍历原型链,寻找displayPrototype是否在原型链上,若找到,返回true

implicitPrototypenull时,结束寻找,没有找到,返回false

原型链其实就是一个类似链表的数据结构。

instanceof做的事,就是在链表上寻找有没有目标节点。从表头节点开始,不断向后遍历,若找到目标节点,返回true。遍历结束还没找到,返回false

3. 验证

写一个简单的实例验证一下自己实现的instanceof

function Person() {}function Person2() {}const usr = new Person();function myInstanceof(obj, constructor) {    let implicitPrototype = obj?.__proto__;    const displayPrototype = constructor.prototype;    while (implicitPrototype) {        if (implicitPrototype === displayPrototype) return true;        implicitPrototype = implicitPrototype.__proto__;    }    return false;}myInstanceof(usr, Person); // truemyInstanceof(usr, Object); // truemyInstanceof(usr, Person2); // falsemyInstanceof(usr, Function); // falsemyInstanceof(usr.__proto__, Person); // falseusr.__proto__ instanceof Person; // false

可以看到,myInstanceof正确得出了结果。

有趣的是,usr.__proto__ instanceof Person返回false,说明obj instanceof constructor检测的原型链,不包括obj节点本身。

JavaScript常见手写代码:

「GitHub
下载地址:
Vue实现跑马灯简单效果
js数组的 entries() 获取迭代方法

万事OK自学网:51自学网_软件自学网_CAD自学网自学excel、自学PS、自学CAD、自学C语言、自学css3实例,是一个通过网络自主学习工作技能的自学平台,网友喜欢的软件自学网站。