instanceof 原理
... 2025-7-10 小于 1 分钟
instanceof 运算符,用于测试构造函数的 prototype 属性,是否出现在对象的原型链中的任何位置。
构造函数的 prototype 属性指向它的原型对象,构造函数的实例的_proto_属性也指向该原型对象。
而且每个对象都有_proto_属性,只有 Object.prototype.__proto__ === null
function Car(mark, model, year) {
this.mark = mark
this.model = model
this.year = year
}
var auto = new Car('Honda', 'Accord', 1998)
console.log(auto instanceof Car) //true
console.log(auto instanceof Object) //true
1
2
3
4
5
6
7
8
9
10
2
3
4
5
6
7
8
9
10
instanceof 实现的原理:
判断构造函数的原型对象(如 Car.prototype 和 Object.prototype)是否在实例对象(auto)的原型链上(proto);
如果在对象的原型链上,就返回 true,如果不在就返回 false;
跨 frame 或 window 的情况
同一个页面中不同的 frame 之间,以及主页面与 frame 之间,有着不同的上下文执行环境,和不同的内置对象。当 instanceof 操作符涉及到多个 frame 时,就会出现一些非预期的情况:
;[] instanceof window.frames[0].Array // false
1
因为 [] 是由主页面中的 Array 生成的,跟 frame 中的 Array 并无关联。
当页面中有多个 frame 之间的数据交换时,要特别注意这一点。