1. 语法上的不同
// typeoftypeof 123 // Number// instanceoffunction 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); // trueconsole.log(auto instanceof Object); // true
2. 本质上的不同
2.1 typeof
- typeof 是针对变量自身,返回一个字符串,表示当前变量的类型;
typeof 对复杂数据返回都是 ‘object’,无法区分数组,对象,函数,同时 typeof null === ‘object’;
instanceof
instanceof 运算符用于检测构造函数的 prototype 属性是否出现在某个实例对象的原型链上;所以它可以准确的判断变量的类型;
- 但是对于基本数据类型,无法判断通过字面量方式创建的类型,只能通过 new 的形式创建的类型。
var str1 = '这是一个字符串'var str2 = new String('这是一个字符串')str1 instanceof String // falsestr2 instanceof String // true
