typeof和instanceof的区别
typeof可以判断数据类型,一般返回string、number、object、boolean、undefined、function。
用法:
typeof 'str' //string
typeof 1 //number
let a = fuctiong(){}
typeof a //function
在实际应用当中,当我们遇到null、object、array,以及某个实例函数时使用typeof判断类型,都会返回object,所以无法确定真正的数据类型,由此引申出instanceof。
instanceof
instanceof
运算符用于检测构造函数的 prototype
属性是否出现在某个实例对象的原型链上
let a = new Array();
console.log(a instanceof Array);//true 检查数组
function C(){}
functionD(){}
let o = new C()
o instanceof C //true 因为Object.getPrototypeof(o) === C.prototype
o instanceof D //false 因为D.prototype 不在o的原型链上;
C.prototype = {};
let o2 = new C();
C.prototype = {};
o2 instanceof C //true
o instanceof C //false C.prototype指向了一个空对象,这个对象不在o的原型链上;
D.prototype = new C();//继承;
let o3 = new D();
o3 instanceof C //true; 因为C.prototype 出现在o3的原型链上
o3 instanceof D //true;
参考:https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Operators/instanceof