javascript - instanceof运算符
本文介绍了javascript - instanceof运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
问 题
https://www.ibm.com/developer...
根据此文
instaceof可以用下列代码模拟
function instance_of(L, R) {//L 表示左表达式,R 表示右表达式
var O = R.prototype;// 取 R 的显示原型
L = L.__proto__;// 取 L 的隐式原型
while (true) {
if (L === null)
return false;
if (O === L)// 这里重点:当 O 严格等于 L 时,返回 true
return true;
L = L.__proto__;
}
}
但是
var a=1;
instance_of(a,Object)为true
a instanceof Object却返回false,这是为什么?
解决方案
楼主,你可以试一试 你的 instance_of
是代替不了 instanceof
的
首先,明确你的样本 a 是Number 类型
但是,执行结果如下
instance_of(a, Object) // true
instance_of(a, Number) // true
修改 instance_of 方法:
function instance_of(L, R) {
try {
var O = R.prototype;// 取 R 的显示原型
L = Object.getPrototypeOf(L);// 取 L 的隐式原型
while (true) {
if (L === null)
return false;
if (O === L)// 这里重点:当 O 严格等于 L 时,返回 true
return true;
L = L.Object.getPrototypeOf(L);
}
} catch (e) {
return false
}
}
再次实验:
var a = 1
instance_of(a, Object) // false
instance_of(a, Number) // true
var parent = function () {}
var child = new parent()
instance_of(child, parent) // true
这篇关于javascript - instanceof运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文