zoukankan      html  css  js  c++  java
  • javascript中typeof和instanceof用法的总结

    今天在看相应的javascript书籍时,遇到了typeof和instanceof的问题,一直不太懂,特地查资料总结如下:

    JavaScript 中 typeof 和 instanceof 常用来判断是什么类型的。但它们之间还是有区别的:

    typeof

    typeof 是一个一元运算,放在一个运算数之前,运算数可以是任意类型。

    它返回值是一个字符串,该字符串说明运算数的类型。typeof 一般只能返回如下几个结果:

    number,boolean,string,function,object,undefined

    先看例子:

    var a= 1;
    console.log(typeof a); //number

    var b= '1'; console.log(typeof b); //string

    var c; console.log(typeof c); //undefined

    var d= true; console.log(typeof d); //boolean

    var e= [1,2,3]; console.log(typeof e); //object

    var f= function(){}; console.log(typeof f); //function

    【插一句:注意一点,返回值number, string, undefined, function,boolean,object这些都是字符串,类型都是string。】

    上面我们看到:

    观察输出结果发现,number, string, undefined, function,boolean类型均能通过typeof方法判断,而array类型输出object。

    因为typeof方法只能判断基本类型类型有(number, string, undefined,boolean,function【函数】),而当判断NULL,数组,对象这三种的情况时,一般都返回object。

    除此之外(包括Date, RegExp,null等都只是object的扩展!),返回的都是object。

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

    正因为typeof遇到null,数组,对象时都会返回object类型,所以当我们要判断一个对象是否是数组时,或者判断某个变量是否是某个对象的实例则要选择使用另一个关键语法instanceof。

    instanceof

    instance:实例,例子

    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。

    另外,更重的一点是 instanceof 可以在继承关系中用来判断一个实例是否属于它的父类型。

    有关instanceof的详细用法可参考:http://www.studyofnet.com/news/175.html

  • 相关阅读:
    UML——六大关系整理
    C#编写Windows 服务
    Centos7下lamp环境搭建的小笔记
    awk命令分析日志的简单笔记
    ssrf小记
    关于cookie的一些学习笔记
    xssbypass小记
    xss挑战赛小记 0x03(xssgame)
    xss挑战赛小记 0x01(xsstest)
    ubuntu下安装LAMP环境遇到的一些小问题
  • 原文地址:https://www.cnblogs.com/wangzhenhai/p/6646430.html
Copyright © 2011-2022 走看看