`
DBear
  • 浏览: 228616 次
  • 性别: Icon_minigender_2
  • 来自: 上海
社区版块
存档分类

JavaScript精炼---typeof与instanceof

阅读更多

 

typeof

 

使用方法:typeof(i) 

   返回值:

 

  • primitive型: "number", "string", "boolean" 
  • arrays, null, String, Number, Boolean, Date, RegExp, objects, all client-side objects: "object" 
  • function: "function" 
  • undefined: "undefined" 

 

        目的:简单说,typeof方法用于判断目标为何种类型数据,判断结果如上所示。因此我们可以用它来判断一个数据是不是对象,是不是函数,是不是未定义,以及是哪种primitive类型。

 

instanceof

使用方法:object instanceof class 

   返回值:true/false

      目的:instanceof用于判断一个实例object是不是某类class的实例。因此,判断的前提是object是对象实例,class是一个类。如:

 

  1. var Car(){
  2. }

  3. var car = new Car();
  4. document.write(car instanceof Car); // prints true;

  1. var Car(){
  2. }
  3.  
  4. var Animal(){
  5. }
  6.  
  7. Car.prototype = new Animal(); 
  8. var car = new Car();
  9.  
  10. document.write(car instanceof Animal); // prints true;
     因此,instanceof 是从prototype中去查找的。

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics