instanceof解析
2016/02/21
instanceof
运算符用于检测构造函数的prototype属性是否出现在某个实例对象的原型链上.
语法
// object: 某个实例对象
// constrictor: 某个构造函数
object instanceof constructor
示例
// 定义构造函数
function C(){}
function D(){}
var o = new C();
o instanceof C; // true,因为 Object.getPrototypeOf(o) === C.prototype
o instanceof D; // false,因为 D.prototype 不在 o 的原型链上
o instanceof Object; // true,因为 Object.prototype.isPrototypeOf(o) 返回 true
C.prototype instanceof Object // true,同上
C.prototype = {};
var o2 = new C();
o2 instanceof C; // true
o instanceof C; // false,C.prototype 指向了一个空对象,这个空对象不在 o 的原型链上.
D.prototype = new C(); // 继承
var o3 = new D();
o3 instanceof D; // true
o3 instanceof C; // true 因为 C.prototype 现在在 o3 的原型链上
注意事项
const a = "this is string a"
const b = "this is string b"
a instanceof String // false,因为a不是实例对象
b instanceof String // true
不是...的实例
const a = new String('a')
if (!(a instanceof String)) {} // 正确写法
if (!a instanceof String) {} // 错误写法,会先运行!a
实现原理
const new_instanceof = function (left, right) {
if (left === null) return false
if ((typeof left !== 'object') && (typeof left !== 'function')) return false // 基本数据类型直接返回false
let left_proto = left.__proto__
const right_proto = right.prototype
while(true) {
if (left_proto === null) return false
if (left_proto === right_proto) {
return true
} else {
left_proto = left_proto.__proto__
}
}
}