1.typeof 能判断出字符串、数字、方法和undefined,array、null、object判断不出
let num = 1;
let str = "x";
let fn = function user(){}
let arr = [1,2]
let obj = {name:"zhangs"}
let und;
let nul = null;
console.log(typeof num) //number
console.log(typeof str) //string
console.log(typeof fn)//function
console.log(typeof und) //undefined
console.log(typeof arr) //object
console.log(typeof obj) //object
console.log(typeof nul) //object
- instanceof 如 a instanceof b, 判断a的原型链上是否有b的原型
let fn = function user(){}
let arr = [1,2]
let obj = {name:"zhangs"}
let und;
console.log(fn instanceof Function) //true
console.log(arr instanceof Array) //true
console.log(arr instanceof Object) //true
console.log(obj instanceof Object) //true
-
Object.getPrototypeOf() 返回参数的隐式原型 ,感觉有些鸡肋
Object.getPrototypeOf ([]) === Array.prototype //true -
Object.prototype.toString.call()
这里解释一下为什么Object.prototype.toString 可以调用call方法,首先我们知道call方法来源,它来自Function.prototype,
这是因为Object.prototype.toString 本身是一个方法,是方法它的原型链上就会出现Function的原型对象,所有就有了call方法,这跟一个对象如let obj= {},obj可以使用toString一个意思,因为toString在Object.prototype上。
let num = 1;
let str = "x";
let fn = function user(){}
let arr = [1,2]
let obj = {name:"zhangs"}
let und;
let nul = null;
console.log(Object.prototype.toString.call(obj)); //[object Object]
console.log(Object.prototype.toString.call(fn)); //[object Function]
console.log(Object.prototype.toString.call(arr)); //[object Array]
console.log(Object.prototype.toString.call(nul)); //[object Null]
console.log(Object.prototype.toString.call(und)); //[object Undefined]
console.log(Object.prototype.toString.call(num)); //[object Number]
console.log(Object.prototype.toString.call(str)); //[object String]
这种方式还是挺万能的,没看出来有什么局限性