instanceof
用法 A instanceof B
官方说法是
用于测试构造函数的prototype(B)属性是否出现在对象(A)的原型链的任何位置,即constructor.prototype(A)是否存在于object(B)的原型链
function Animal(head, feet, tail){
this.head = head
this.feet = feet
this.tail = tail
}
let animal = new Animal(1, 4, 1)
console.log(animal instanceof Animal) //true
没毛病,Animal的prototype出现在animal的原型链上
function Cat(name, age){
this.name = name
this.age = age
}
Cat.prototype = new Animal(1, 4, 1)
let cat = new Cat('Tom', 2)
console.log(cat instanceof Animal) //true
只要B.prototype在A的原型链上的任何位置都会返回true
注意
let str1 = "Hello world"
let str2 = new String()
let str3 = new String("Hello world")
console.log(str1 instanceof String) //false str1并不是对象,而是一个基本类型,他没有原型链,其他基本类型同样
console.log(str2 instanceof String) //true
console.log(str3 instanceof String) //true
typeof
typeof用来检测数据类型,不过它只能准确地判断boolean , string , number, undefined, function ,symbol这几个类型,其他的都会返回object
console.log(typeof false);
console.log(typeof "tom");
console.log(typeof 2);
console.log(typeof undefined);
console.log(typeof function (){});
console.log(typeof Symbol());
注意:typeof 的返回值都是字符串类型,即 typeof (typeof obj) == "string"
Object.prototype.toString.call()
使用Object.prototype原生的toString()判断数据类型
我jio的这个方法是最强大的一个了
console.log(Object.prototype.toString.call("")) //[object String]
console.log(Object.prototype.toString.call(1)) //[object Number]
console.log(Object.prototype.toString.call(true)) //[object Boolean]
console.log(Object.prototype.toString.call(Symbol())) //[object Symbol]
console.log(Object.prototype.toString.call(undefined)) //[object Undefined]
console.log(Object.prototype.toString.call(null)) //[object Null]
console.log(Object.prototype.toString.call({})) //[object Object]
console.log(Object.prototype.toString.call(function (){})) //[object Function]
console.log(Object.prototype.toString.call(NaN)) //[object Number]
console.log(Object.prototype.toString.call([])) //[object Array]
只有number和NaN分辨不出来,NaN可以用isNaN()来判断