instanceof运算符用于测试构造函数的prototype属性是否出现在对象的原型链中的任何位置
function Car(make, model, year) {
this.make = make;
this.model = model;
this.year = year;
}
var auto = new Car('Honda', 'Accord', 1998);
console.log(auto instanceof Car);
// : true
console.log(auto instanceof Object);
// true
instanceof 可以正确的判断对象的类型,因为内部机制是通过判断对象的原型链中是不是能找到类型的 prototype
实现一个instanceof
function myInstanceof(left, right) {
let prototype = right.prototype
left = left.__proto__
while (true) {
if (left === null || left === undefined)
return false
if (prototype === left)
return true
left = left.__proto__
}
}
1.首先获取类型的原型
2.然后获得对象的原型
3.然后一直循环判断对象的原型是否等于类型的原型,直到对象原型为 null,因为原型链最终为 null
typeof操作符返回一个字符串,表示未经计算的操作数的类型
typeof 对于原始类型来说,除了 null 都可以显示正确的类型
typeof 1 // 'number'
typeof '1' // 'string'
typeof undefined // 'undefined'
typeof true // 'boolean'
typeof Symbol() // 'symbol'
typeof 对于对象来说,除了函数都会显示 object,所以说 typeof 并不能准确判断变量到底是什么类型
typeof [] // 'object'
typeof {} // 'object'
typeof console.log // 'function'
另外typeof null 也是’object’ ,这是一个特殊情况,null是基本类型