区别
- typeof:
- 功能:返回一个表示操作数类型的字符串,主要用于检测基本数据类型(
number
、string
、boolean
、undefined
、symbol
)以及函数类型。对于对象类型,除了函数会返回'function'
外,其他对象类型统一返回'object'
。
- 语法:
typeof operand
,其中operand
是要检测的变量或值。
- instanceof:
- 功能:用于检测构造函数的
prototype
属性是否出现在某个实例对象的原型链上,主要用于检测对象的具体类型,判断一个对象是否是某个构造函数的实例。
- 语法:
object instanceof constructor
,其中object
是要检测的对象,constructor
是构造函数。
场景举例
- typeof使用场景:
console.log(typeof 123); // 'number'
console.log(typeof 'hello'); //'string'
console.log(typeof true); // 'boolean'
console.log(typeof undefined); // 'undefined'
console.log(typeof Symbol()); //'symbol'
function test() {}
console.log(typeof test); // 'function'
- instanceof使用场景:
function Person(name) {
this.name = name;
}
let person1 = new Person('John');
console.log(person1 instanceof Person); // true
let arr = [];
console.log(arr instanceof Array); // true
function Animal() {}
function Dog() {}
Dog.prototype = new Animal();
let dog1 = new Dog();
console.log(dog1 instanceof Dog); // true
console.log(dog1 instanceof Animal); // true