【JS基础】instanceof 和 typeof

 

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)

posted @ 2023-06-23 21:45  zjy4fun  阅读(7)  评论(0编辑  收藏  举报