instanceof与typeof的区别
typeof 判断 值得类型
instanceof 判断 是否是某一对象的实例
console.log(typeof 11) // number
console.log( {} instanceof Object ) // true
typeof有哪些值
- string
- number
- object
- undefined
- symbol
- function
- boolean
// string
console.log( typeof '一一' === string ) // true
// number
console.log( typeof 11 === number ) // true
// function
console.log( typeof (()=>{}) === function ) // true
// undefined
console.log( typeof undefined === undefined ) // true
// symbol
console.log( typeof Symbol() === symbol ) // true
// boolean
console.log( typeof true === boolean ) // true
// object
console.log( typeof null === object ) // true
console.log( typeof {} === object ) // true
console.log( typeof [] === object ) // true
instanceof的一些特殊情况
- 直接创建字符串时,检查原型会找到undefined
- 创建非Object实例的对象的方法时,会返回false
- 只要在原型中能查找到对应构造函数,都会返回true
var simpleStr = "This is a simple string";
var myString = new String();
var newStr = new String("String created with constructor");
var myDate = new Date();
var myObj = {};
var myNonObj = Object.create(null);
simpleStr instanceof String; // 返回 false, 检查原型链会找到 undefined
myString instanceof String; // 返回 true
newStr instanceof String; // 返回 true
myString instanceof Object; // 返回 true
myObj instanceof Object; // 返回 true, 尽管原型没有定义
({}) instanceof Object; // 返回 true, 同上
myNonObj instanceof Object; // 返回 false, 一种创建非 Object 实例的对象的方法
myString instanceof Date; //返回 false
myDate instanceof Date; // 返回 true
myDate instanceof Object; // 返回 true
myDate instanceof String; // 返回 false
instanceof的实现
要了解实现,我们先看看instanceof的描述:
instanceof 运算符用来检测 constructor.prototype 是否存在于参数 object 的原型链上。
由这句话我们可以得出结论,只需要遍历原型链中是否有与之对应的构造原型即可
function newInstanceof(leftVaule, rightVaule) {
let rightProto = rightVaule.prototype;
// 取右表达式的 prototype 值 leftVaule = leftVaule.__proto__;
// 取左表达式的__proto__值
while (true) {
if (leftVaule === null) {
return false;
}
if (leftVaule === rightProto) {
return true;
}
leftVaule = leftVaule.__proto__
}
}