function _instanceof(L, R) {
// 左边是基本数据类型直接返回false,因为instanceof判断的是实例
if(
(typeof L !== 'object'
&& typeof L !== 'function')
||L === null
) return false;
// 右边是基本数据类型则抛出错误,instanceof的右边必须是对象
if (
(typeof R !== 'object'
&& typeof R !== 'function')
||R === null
) throw Error("Right-hand side of instanceof is not an object")
// getProtypeOf是Object对象自带的一个方法,能够拿到参数的原型对象
// 这个方法代替.__proto__,__proto__在最新规范中弃用,有些浏览器也不支持
while (true) {
if (Object.getPrototypeOf(L) === null) {
return false
}
if (Object.getPrototypeOf(L) === R.prototype) {
return true
}
L = Object.getPrototypeOf(L)
}
}
[JavaScript]手写一个instanceof
最新推荐文章于 2025-06-10 14:26:16 发布