js中typeof和instanceof的区别。

来源:互联网 发布:怎么查看淘宝买家信誉 编辑:程序博客网 时间:2024/06/05 23:43

1.首先,先介绍js数据类型的分类。

 <1>:从广义上说ECMAScript的数据类型分为2大种:基本数据类 型 和 复杂数据类型 (或复合数据类型);

<2>: 基本数据类型又分为5种——:number,string,boolean,undefined,null;
<3>: 复杂数据类型——object;
 综上所述:狭义上说JavaScript的数据类型分为6种。

2 typeof操作符的返回值有哪几种?

 

var str1="nihao",      num1=15,      bol1=false,      obj1 = {name:'xiaoli',age:18},      arr1 = [1,2,3],      fun = function(){alert(2)},      n = null,      m;console.log(typeof num1);   //numberconsole.log(typeof str1);   //stringconsole.log(typeof bol1);   //booleanconsole.log(typeof obj1);   //objectconsole.log(typeof arr1);   //objectconsole.log(typeof n);      //objectconsole.log(typeof fun);    //functionconsole.log(typeof m);      //undefined
由以上可得:typeof只能够判断出是哪一种基本数据类型或者是否为复杂数据类型,但是在检测引用类型的值时,用处不大。通常我们想知道某个对象是什么类型的对象时,instanceof可以帮助我们。

当变量是给定引用类型的实例,instanceof操作符会返回true。

function  person() {}var  person_1=new person();comsole.log(person_1 instanceof person);//true



原创粉丝点击