`

JavaScript:typeof和instanceof运算符

阅读更多

    对于instanceof和typeof,以前偶尔的用到过,特别是typeof用到的相对更多一些,今日研究ext源码,很多地方都用到了instanceof,突然觉得他们两个有些相似但也应该有他们区别,网上看了一些文章,对它们之间的关系有了一定的了解。 instanceof和typeof都能用来判断一个变量是否为空或是什么类型的变量。 typeof用以获取一个变量的类型,typeof一般只能返回如下几个结果:number,boolean,string,function,object,undefined。我们可以使用typeof来获取一个变量是否存在,

如  if(typeof a!="undefined"){} if(typeof a!="undefined"){} 而不要去使用if(a)因为如果a不存在(未声明)则会出错,对于Array,Null等特殊对象使用typeof一律返回object,这正是typeof的局限性。 如果我们希望获取一个对象是否是数组,或判断某个变量是否是某个对象的实例则要选择使用instanceof。

      instanceof用于判断一个变量是否某个对象的实例,

如  var a=new Array();alert(a instanceof Array);//会返回true

var a=new Array();alert(a instanceof Array);//会返回true

同时 alert(a instanceof Object) //也会返回true

alert(a instanceof Object) //也会返回true 这是因为Array是object的子类。

再如: function test(){};

var a=new test();alert(a instanceof test) //会返回true

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics