typeof
typeof方法返回一个字符串,来表示数据的类型。
各个数据类型对应typeof的值:
| 数据类型 | 
Type | 
| Undefined | 
“undefined” | 
| Null | 
“object” | 
| Boolean | 
“boolean” | 
| Number | 
“number” | 
| String | 
“string” | 
| Symbol | 
“symbol” | 
| 宿主对象(JS环境提供的,比如浏览器) | 
Implementation-dependent | 
| 函数对象Function | 
“function” | 
| 任何其他对象Object | 
“object” | 
下面是代码示例:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
   |  typeof 37 === 'number'; typeof 3.14 === 'number'; typeof Math.LN2 === 'number'; typeof Infinity === 'number'; typeof NaN === 'number';  typeof Number(1) === 'number'; 
 
  typeof "" === 'string'; typeof "bla" === 'string'; typeof (typeof 1) === 'string';  typeof String("abc") === 'string'; 
 
  typeof true === 'boolean'; typeof false === 'boolean'; typeof Boolean(true) === 'boolean'; 
 
  typeof Symbol() === 'symbol'; typeof Symbol('foo') === 'symbol'; typeof Symbol.iterator === 'symbol';
 
  typeof undefined === 'undefined'; typeof blabla === 'undefined'; 
 
  typeof {a:1} === 'object';
 
  typeof [1, 2, 4] === 'object';
  typeof new Date() === 'object';
 
  typeof new Boolean(true) === 'object'; typeof new Number(1) ==== 'object'; typeof new String("abc") === 'object';
 
  typeof function(){} === 'function'; typeof Math.sin === 'function';
 
  | 
 
发现typeof来判断数据类型其实并不准确。比如数组、正则、日期、对象hj的typeof返回值都是object
instanceof
instanceof运算符可以用来判断某个构造函数的prototype属性是否存在于另外一个要检测对象的原型链上。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
   |  function C(){}  function D(){} 
  var o = new C();
 
  o instanceof C; 
 
  o instanceof D; 
  o instanceof Object;  C.prototype instanceof Object 
  C.prototype = {}; var o2 = new C();
  o2 instanceof C; 
  o instanceof C; 
  D.prototype = new C();  var o3 = new D(); o3 instanceof D;  o3 instanceof C; 
 
  |