JavaScript类型检测

2017-09-06  本文已影响0人  yyyzhen

typeof

适合基本类型和函数类型,遇到null失效

typeof 123  // 'number'
typeof ‘string’  // 'string'
typeof false  // 'boolean'
typeof undefined  // 'undefined'
typeof null  // 'object'
typeof function(){}  // 'function'

instanceof

判断左边的原型链上是否有右边构造函数的prototype属性
适合自定义对象,也可以用来检测原生类型,在不同iframe和window之间检测失效

function Person() {}
function Student() {}
var person = new Person
Student.prototype = new Person
var yz = new Student

person instanceof Person  // true
yz instanceof Student  // true
yz instanceof Person  // true

Object.prototype.toString.apply()

通过{}.toString()拿到,适合内置对象和基元类型,遇到null和undefined失效(IE6/7/8等返回[object Object])
[object class]是对象的类属性,用以表达对象的类型信息

Object.prototype.toString.apply(new Array)  // '[object Array]'
Object.prototype.toString.apply(new Date)  // '[object Date]'
Object.prototype.toString.apply(new RegExp)  // '[object Regexp]'
Object.prototype.toString.apply(function(){})  // '[object Function]'
Object.prototype.toString.apply(false)  // '[object Boolean]'
Object.prototype.toString.apply('string')  // '[object String]'
Object.prototype.toString.apply(1)  // '[object Number]'
Object.prototype.toString.apply(undefined)  // [object Undefined]'
Object.prototype.toString.apply(null)  // '[object Null]'
Object.prototype.toString.apply(window)  // '[object Window]'

判断各种类型

  // 代码出自慕课网《JavaScript深入浅出》1-6节
  // 判断String、Number、Boolean、undefined、null、函数、日期、window对象
  function typeof(el) {
    var result
    if (el === null) {
      result = 'null'
    } else if (el instanceof Array) {
      result = 'array'
    } else if (el instanceof Date) {
      result = 'date'
    } else if (el === window) {
      result = 'window'
    } else {
      result = typeof el
    }
    return result
  }

代码分析:

上一篇 下一篇

猜你喜欢

热点阅读