[关闭]
@Lxyour 2018-09-14T13:54:23.000000Z 字数 1422 阅读 778

JS类型检测

JavaScript


typeof

typeof用于检测基本类型,不适合Array、NaN、null

  1. typeof 100 //"number"
  2. typeof true //"boolean"
  3. typeof function //"function"
  4. typeof(undefined) //"undefined"
  5. typeof new Object() //"object"
  6. typeof [0, 2] //"object"
  7. typeof NaN //"number"
  8. typeof null //"object"

typeof null === "object" ?

typeOf选择题测试

instanceof

对于对象类型我们用instanceof更适合。
obj instanceof Object

  1. [1, 2] instanceof Array === true
  2. new Object() instanceof Array === false

Object.prototype.toString

toString 是 Object 原型对象上的方法,使用 call 来调用该方法会返回调用者的类型字符串,格式为 [object,xxx],xxx 是调用者的数据类型,包括:String、Number、Boolean、Undefined、Null、Function、Date、Array、RegExp、Error、HTMLDocument 等, 基本上,所有的数据类型都可以通过这个方法获取到。

  1. Object.prototype.toString.call([]) === "[object Array]";
  2. Object.prototype.toString.call(function () {}) === "[object Function]";
  3. Object.prototype.toString.call(null) === "[object Null]";
  4. Object.prototype.toString.call(undefined) === "[object Undefined]";
  5. Object.prototype.toString.call(null) === "[object Object]"; //IE6/7/8

constructor

当一个函数 F被定义时,JS引擎会为F添加 prototype 原型,然后再在 prototype上添加一个 constructor 属性,并让其指向 F 的引用。如下所示:

  1. function F() {}
  2. F.prototype

当执行 var f = new F() 时,F 被当成了构造函数,f 是F的实例对象,此时 F 原型上的 constructor 传递到了 f 上,因此 f.constructor === F

可以看出,F 利用原型对象上的 constructor 引用了自身,当 F 作为构造函数来创建对象时,原型上的 constructor 就被遗传到了新创建的对象上, 从原型链角度讲,构造函数 F 就是新对象的类型。这样做的意义是,让新对象在诞生以后,就具有可追溯的数据类型。

同样,JavaScript 中的内置对象在内部构建时也是这样做的:

  1. [].constructor === Array // true
  2. ''.constructor === String // true

duck type

根据数据类型的特征来判断,比如可以检测是否有push()方法来判定Array;

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注