JavaScript instanceof
function Person(name) {
this.name = name;
}
var person = new Person('小明');
console.log(
person instanceof Person,
); // 输出:true
1. 语法
对象 instanceof 构造函数;
否则会报如下错误:
[] instanceof {};
// Uncaught TypeError: Right-hand side of 'instanceof' is not callable
2. 注意点
使用 instanceof
检测的时候,不一定只有一个为 true
的结果。
function Person(name) {
this.name = name;
}
var person = new Person('小明');
console.log(
person instanceof Person,
person instanceof Object,
); // 输出:true
因为 instanceof
实际上是去左操作数的原型链上寻找有没有右操作数的原型
。
person
的原型链上既匹配到 Person.prototype
又能匹配到 Object.prototype
,所以都能返回 true
。
使用的时候要注意这个问题,如判断某个对象的原型链上是否有 Object.prototype
的时候,要考虑到一些其他对象。
[] instanceof Object; // true
数组的原型链上也是有 Object.prototype
的,所以做一些检测的时候要考虑一些特殊情况。