js类型检测

88 阅读1分钟
  1. typeof
    适用于基本类型和函数的检测 遇到null无效

    • typeof 100 -> "number"
    • typeof true -> "boolean"
    • typeof function -> "function"
    • typeof (undefined) -> "undefined"
    • typeof new Object() -> "object"
    • typeof [1,2] -> "object"
    • typeof NaN -> "number"
    • typeof null -> "object"
  2. instanceof obj instanceof Object
    适合自定义对象,也可用来检测原生对象,在不同iframe和window间检测时失效 判断左边的操作数对象的原型链上是否有右侧的构造函数的属性

    • [1,2] instanceof Array === true
    • new Object() instanceof Array === false
    function Person(){}  //undefined
    function Student(){} //undefined
    Student.prototype = new Person()  //Person
    Student.prototype.constructor = Student // function Student(){}
    var bosn = new Student() //undefined
    bosn instanceof Student //true
    var one = new Person() //undefined
    one instanceof Person //true
    one instanceof Student // false
    bosn instanceof Person //true
    
  3. Object.prototype.toString
    适合内置对象和基元类型,遇到null和undefined失效

    • Object.prototype.toString.apply([]) === "[object Array]";
    • Object.prototype.toString.apply(function(){}]) === "[object Function]";
    • Object.prototype.toString.apply(null) === "[object Null]";
    • Object.prototype.toString.apply(undefined) === "[object Undefined]"; 注:IE6/7/8 Object.prototype.toString.apply(null) === "[object Object]"
  4. constructor 继承自己原型

  5. duck type