【JS基础】instanceof 和 typeof

发布时间 2023-06-23 21:47:20作者: zjy4fun

 

instanceof 运算符用于检测构造函数的 prototype 属性是否出现在某个实例对象的原型链上。

object instanceof constructor

typeof 运算符返回一个字符串,表示操作数的类型。

typeof operand
console.log('--------------------  instanceof  -------------------')
// typeof check if an object is an instance of a particular constructor
// check the prototype chain of the object to determine if the constructor appears in it

// create a constructor function
function Person(name) {
    this.name = name
}

const person = new Person('John');

console.log(person instanceof Person) // true

console.log(person instanceof Object) // true

console.log([] instanceof Array) // true

console.log('--------------------  typeof  -------------------');
// typeof is used to determine the type of a value or variable.
// It returns a string indicating the type of the operand.
console.log(typeof 42) //number

 

参考:

instanceof - JavaScript | MDN (mozilla.org)

typeof - JavaScript | MDN (mozilla.org)