instanceof 运算符
instanceof #
instanceof
运算符用于检测构造函数的 prototype
属性是否出现在某个实例对象的原型链上。
语法 #
object instanceof constructor;
1
参数 #
object
: 某个实例对象constructor
: 某个构造函数
示例 #
function Car(make, model, year) {
this.make = make;
this.model = model;
this.year = year;
}
const 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
2
3
4
5
6
7
8
手写实现 #
function instabceof(target, origin) {
while (target) {
if (Object.getPrototypeOf(target) === origin.prototype) return true;
target = Object.getPrototypeOf(target);
}
return false;
}
console.log(instabceof(auto, Car)); // true
console.log(instabceof(auto, Object)); // true
1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
编辑 (opens new window)
上次更新: 2021-06-23 08:43:55