JavaScript高级程序设计(五): js的关键字instanceof和typeof使用

 JavaScript中instanceof和typeof 常用来判断一个变量是否为空,或者是什么类型的。但它们之间还是有区别的:

 一、typeof

  1、含义:typeof返回一个表达式的数据类型的字符串,返回结果为js基本的数据类型,包括number,boolean,string,object,undefined,function.语法为typeof(data) 或 typeof data.

  我们可以使用typeof来获取一个变量是否存在,如:

if(typeof a!='undefined'){
alert(''ok);
}

最好不要使用if(a),因为如果a不存在(未声明)则会出错,对于Array,null等特殊对象使用typeof一律返回object,这正是typeof的局限性。

二、instanceof

instanceof则为判断一个对象是否为某一数据类型,或一个变量是否为一个对象的实例;返回boolean类型
语法为 o instanceof A.

var o={};
18alert("h instanceof Person:" + (h instanceof Person));//true
19alert("h instanceof Object:" + (h instanceof Object));//true
20alert("o instanceof Object:" + (o instanceof Object));//true
原文地址:https://www.cnblogs.com/renxiaoren/p/5941490.html