zoukankan      html  css  js  c++  java
  • JavaScript instanceof和typeof的区别

    引用自:   http://www.cnblogs.com/eoiioe/archive/2008/12/31/1366081.html 

    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。

         谈到instanceof我们要多插入一个问题,就是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'(chome 实测为 Y)

      所以,这里的instanceof测试的object是指 js 语法中的 object,不是指 dom 模型对象。

      使用typeof会有些区别
      alert(typeof(window) 会得 object

  • 相关阅读:
    spring注解之@Lazy
    HttpClient之EntityUtils对象
    HTTP协议(Requset、Response)
    SpringBoot SpringSession redis SESSION
    Spring-session redis 子域名 session
    Spring Boot Servlet
    版本管理
    Spring AOP @Aspect
    Spring 事务配置的五种方式
    Spring <tx:annotation-driven>注解 JDK动态代理和CGLIB动态代理 区别。
  • 原文地址:https://www.cnblogs.com/muyiblog/p/5781798.html
Copyright © 2011-2022 走看看