码迷,mamicode.com
首页 > Web开发 > 详细

JS中有哪些识别类型的方法

时间:2015-10-18 00:57:22      阅读:227      评论:0      收藏:0      [点我收藏+]

标签:

  1. //1.使用typeof..
  2. //无需封装直接使用.
  3. //可以识别标志类型(null除外)
  4. //不可识别具体的对象类型
  5. typeof(1);//"number"
  6. typeof("");//"string"
  7. typeof([]);//"object"
  8. typeof({});//"object"
  9. typeof(null);//"object"
  10. typeof(undefined);//"undefined"
  11.  
  12. //2.instanceof
  13. //无须封装使用
  14. //能够判别内置对象类型
  15. [] instanceof Array;//true
  16. /\d/ instanceof RegExp;//true
  17. //不能判别原始类型
  18. instanceof Number;//false
  19. "xiaohong" instanceof String;//false
  20. //能够判别自定义类型
  21. function Point(x, y) {
  22.     this.x = x;
  23.     this.y = y;
  24. }
  25. var c = new Point(2,3);
  26. instanceof Point;//true
  27.  
  28. //3.Object.prototype.toString.call()方法.
  29. Object.prototype.toString.call(21);//"[object Number]"
  30. Object.prototype.toString.call([]);//"[object Array]"
  31. //为了方便使用一般都是使用函数封装如下
  32. function typePrototype(obj) {
  33.     return Object.prototype.toString.call(obj).slice(8,-1);
  34. }
  35. typePrototype("guo");//"String"
  36. typePrototype({});//"Object"
  37. //可以识别标准类型,及内置对象类型
  38. //不能识别自定义类型
  39.  
  40.  
  41. //4.constuructor指向构造这个对象的构造函数本身..
  42. //可判别原始类型
  43. "guo".constructor === String;//true
  44. (1).constructor === Number;//true
  45. true.constructor === Boolean;//true
  46. ({}).constructor === Object;//true
  47. //可判别内置对象类型
  48. new Date().constructor === Date;//true
  49. [].constructor === Array;//true
  50.  
  51. //可识别自定义类型
  52. function People(x, y) {
  53.     this.x = x;
  54.     this.y = y;
  55. }
  56. var c = new People(2,3);
  57. c.constructor===People;//true
  58. //函数封装如下
  59. function getConstructorName(obj){
  60.     return obj && obj.constructor && obj.constructor.toString().match(/function\s*([^(]*)/)[1];
  61. }
  62. //利用&&短路特性
  63. //1 obj//如果入参是undefined和null时能够直接返回,因为其没有constructor值
  64. //2 obj.constructor//保证后面的表达式能够正确被执行
  65. //3 obj.constructor.toString()//把构造函数转化为字符串"function Number(){}"
  66. //4 .match(/function\s*([^(]*)/)[1]//获取构造函数字符串中有类型的值"Number"
  67. getConstructorName(new Date());//"Date"
  68. getConstructorName(null);//null
  69. getConstructorName(12);//"Number"

JS中有哪些识别类型的方法

标签:

原文地址:http://www.cnblogs.com/nullObj/p/4888587.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!