2、手写 instanceof 方法
instancecof用于检测一个对象是否是某个构造函数的实例。它通常用于检查对象的类型,尤其是在处理继承关系时。
eg:
const arr = [1,2,3,4,5]console.log(arr instanceof Array); // trueconsole.log(arr instanceof Object); // true
那这是怎么实现的呢?
- 每个对象都有一个原型,对象从其原型继承属性和方法。
- 数组的直接原型是
Array.prototype
。 Array.prototype
的原型是Object.prototype
。Object.prototype
的原型是null
,表示原型链的终点。
这种原型链机制是 JavaScript 继承和原型继承的基础。通过原型链,JavaScript 实现了对象的属性和方法的继承。
我们就知道:
console.log(arr.__proto__ === Array.prototype); // trueconsole.log(arr.__proto__=== Object.prototype); // trueconsole.log(arr.__proto__.__proto__ === Object.prototype); // trueconsole.log(arr.__proto__.__proto__.__proto__ === null); // true
这就让我想到本道题木的解题思路:
在函数当中我们输入目标和待测类型,进行循环,如果原型链上有待测类型的原型返回true,没有也就是当了原型链的终点null,返回false
我的代码:
function getIncetanceof(target , type){// 1、target的原型链let targetProto = target.__proto__;// 2、循环判断while(true){if(targetProto === null){return false;}else if(targetProto === type.prototype){return true;}else{// 都没有的时候就要更新targetPrototargetProto = targetProto.__proto__;}}}