js 类型检测

155 阅读1分钟

1. instanceof

通常 instanceof 就是用来判断某个实例是否属于某种类型

1. 
[] instanceof Array // true;

2.
function Animal(name){
  this.name = name;
}
var dog = new Animal('dog');
dog instanceof Animal // true;

但是还有一种情况,instanceof 可以用于检测一个实例是否属于它的父类型;

function Animal(){}
function Dog(){}
Dog.prototype = new Animal();
var little = new Dog();
little instanceof Animal // true

instanceof 逻辑大概是这个样子的:

function instance_of(L, R) {//L 表示左表达式,R 表示右表达式
 var O = R.prototype;// 取 R 的显示原型
 L = L.__proto__;// 取 L 的隐式原型
 while (true) { 
   if (L === null) 
     return false; 
   if (O === L)// 这里重点:当 O 严格等于 L 时,返回 true 
     return true; 
   L = L.__proto__;  // 从原型链一直往上找,直到Object.__proto__ == null
 } 
}

摘至:https://www.ibm.com/developerworks/cn/web/1306_jiangjj_jsinstanceof/index.html

2. typeof

typeof 11 // "number"
typeof 'sss'  // "string"
typeof null // "object"
typeof undefined  // "undefined"
typeof new Number()  // "object"
typeof new String()  // "object"
typeof Object  // "function"
typeof new Object()  // "object"
typeof Number  // "function"

3. Object.prototype.toString

Object.prototype.toString.call([1,2])  // "[object Array]"
Object.prototype.toString.call({})  // "[object Object]"
Object.prototype.toString.call(function(){})  // "[object Function]"
Object.prototype.toString.call(12)  // "[object Number]"
Object.prototype.toString.call('sss')  // "[object String]"
Object.prototype.toString.call(null)  // "[object Null]"
Object.prototype.toString.call(undefined)  // "[object Undefined]"
Object.prototype.toString.call(Boolean)  // "[object Function]"
Object.prototype.toString.call(true)  // "[object Boolean]"