您的位置:首页 > 其它

自己不官方的理解typeof和instanceof

2017-02-16 16:32 357 查看
一、typeof

     typeof(的)运算数未定义,返回(的)就是 "undefined".

    运算数为数字 typeof(x) = "number"

    字符串 typeof(x) = "string"

    布尔值 typeof(x) = "boolean"

    对象,数组和null typeof(x) = "object"

    函数 typeof(x) = "function"

    综上所述,typeof的返回类型有:undefined,number,string,boolean,object,function

    自己理解的用途:

    我们可以使用 typeof 来获取一个变量是否存在,如 if(typeof a!="undefined"){alert("ok")},而不要去使用 if(a) 因为如果 a 不存在(未   声明)则会出错。

二、instanceof

      instanceof运算符是返回一个 Boolean 值,指出对象是否是特定类的一个实例.

      a instanceof b?alert("true"):alert("false"); //a是b的实例?真:假

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 instanceof