JavaScript中的Instanceof运算子

运算符的实例测试构造函数的prototype属性是否出现在对象的原型链中的任何位置。在更简单的语言中,它测试变量是否为某种类型。但是它有一些警告。让我们看一些例子。

原语

字符串和数字是原始值,不是对象,因此没有[[Prototype]],因此仅当将它们包装在常规对象中时,它才有效。

示例

console.log(1 instanceof Number)
console.log(new Number(1) instanceof Number)
console.log("" instanceof String)
console.log(new String("") instanceof String)

输出结果

false
true
false
true

可构造的功能

返回其对象的函数(JS类)可以使用instanceof运算符检查其对象。

示例

function Person(name) {
   this.name = name
}
let john = new Person("John");
console.log(john instanceof Person)

输出结果

true

传承

JS支持原型继承,因此,如果您检查层次结构中任何类的instanceof,它将返回true。

示例

class Person {}
class Student extends Person {
   constructor(name) {
      super()      this.name = name
   }
}
let john = new Student("John");
console.log(john instanceof Person)
console.log(john instanceof Student)

输出结果

true
true