JavaScript中instanceof运算符的用法以及和typeof的区别

instanceof : 判断一个对象是否为某一数据类型,或一个变量是否为一个对象的实例;返回boolean类型
栗子①:
var aColors = ["red", "green", "blue"]; 
alert(typeof aColors[0]);    //"string" 
alert(aColors[0] instanceof String);    //"false"
alert(aColors instanceof Array); //true

你要区分string 与 String的区别 , aColors[0] 是 string值类型, 当然不是String的实例啦。

参考下面代码 

var aColors = ["red", "green", "blue"]; 
aColors[0]= new String("1") 
alert(typeof aColors[0]); //output "Object" 
alert(aColors[0] instanceof String); //output "true";

instanceof和typeof都能用来判断一个变量是否为空或是什么类型的变量。 

typeof:用以获取一个变量的类型,typeof一般只能返回如下几个结果:number,boolean,string,function,object,undefined

我们可以使用typeof来获取一个变量是否存在,如if(typeof a!="undefined"){},而不要去使用if(a)因为如果a不存在(未声明)则会出错,对于Array,Null等特殊对象使用typeof 一律返回object,这正是typeof的局限性。 

如果我们希望获取一个对象是否是数组,或判断某个变量是否是某个对象的实例则要选择使用instanceof

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

function的arguments,我们大家也许都认为arguments是一个Array,但如果使用instaceof去测试会发现arguments不是一个Array对象,尽管看起来很像。 

 测试 

var a=new Array();
if (a instanceof Object) 
  alert('Y');
else alert('N');   //Y

但 :

if (window instanceof Object) 
  alert('Y');
else alert('N');    //N

所以,这里的instanceof测试的object是指js语法中的object,不是指dom模型对象。 
使用typeof会有些区别 

 alert(typeof(window)    //会得 object 

 

年轻的时候,少说废话,多做事。

摘自:http://www.jb51.net/article/22717.htm

posted @ 2016-08-21 10:34  晴晴加油  阅读(710)  评论(0编辑  收藏  举报