JavaScript中 typeof 和 instanceof 区别
这属于js基础知识,正因为太基础,所以很容易被忽略,导致项目中随处可以见的滥用。
一、typeof
typeof 其实就是判断参数是什么类型的实例,就一个参数,用例:typeof a。
返回值:"number"、"string"、"boolean"、"object"、"function" 、 "undefined"。
typeof 12; // number
typeof 'gym'; // string
typeof !!’0’; // boolean
typeof new Function(); // function
typeof something; // undefined
这里扩展一下,用 typeof 判断变量是否存在:
if(!type) return; //此时若type未定义,将报错:type is not definedif(typeof type === 'undefined') return; //此方法较严谨,能避免异常
用 typeof
来判断引用类型:
let arr = [1,2,3];
let people = {name: 'gymMan'};
let obj = null;typeof arr; // object
typeof people; // object
typeof obj; // object
由此可看出 typeo f判断引用类型的数据返回都未object,无法做到精确判断,我们来总结一下:
1.对于基本类型,除 null
以外,均可以返回正确的结果。
2.对于引用类型,除 function
以外,一律返回 object
类型。
3.对于 null
,返回 object
类型。
4.对于 function
返回 function
类型。
二、instanceof
instanceof
是用来判断 a 是否为 b 的实例,表达式为:a instanceof b
,如果 a 是 b 的实例,则返回 true
,否则返回 false
。
[] instanceof Array; //true
[] instanceof Object; //true ,js中万物皆对象({}) instanceof Object;//true
new Date() instanceof Date;//truefunction Person(){};
new Person() instanceof Person; // true
new Person instanceof Object; // true//通过一个简单的继承来说明
function Parent(){};
function Child(){};
function Other(){};Child.prototype = new Parent();
let child = new Child();child instanceof Child; // true
child instanceof Parent; // true
child instanceof Object; // true
child instanceof Other; // false