typeof与instanceof的区别

typeof用以获取一个变量或者表达式的类型,typeof一般只能返回如下几个结果:

number,boolean,string,function(函数),object(NULL,数组,对象),undefined。

=========================================================

instanceof用于判断一个变量是否某个对象的实例,返回布尔值,如:

var a=new Array();

alert(a instanceof Array);//true

alert(a instanceof Object);//true 因为Array是object的子类。

  

function test(){};

var a=new test();

alert(a instanceof test);//true。

  

=========================================================

正因为typeof遇到null,数组,对象时都会返回object类型

所以当我们要判断一个对象是否是数组或者某个变量是否是某个对象的实例则要选择使用instanceof

原文地址:https://www.cnblogs.com/dtdxrk/p/4126207.html