let arr = [1,2,3]
- arr instanceof Array ==> boolean 判断一个对象是否为某个类(构造函数)的实例
- Array.isArray(arr) ==> boolean
- arr.constructor === Array
- Object.getPropertyOf(arr) === Array.prototype
function myInstanceOf(obj, constructor) {
// 检查参数是否为函数
if (typeof constructor !== 'function') {
throw new Error('Right-hand side of \'instanceof\' is not callable');
}
// 检查参数是否为对象
if (obj === null || (typeof obj !== 'object' && typeof obj !== 'function')) {
return false;
}
let prototype = Object.getPrototypeOf(obj); // 获取对象的原型
while (prototype !== null) {
if (prototype === constructor.prototype) {
return true;
}
prototype = Object.getPrototypeOf(prototype); // 沿原型链向上查找
}
return false; // 如果没有找到匹配的原型,则返回 false
}