typeof
typeof 运算符返回一个用来表示表达式的数据类型的字符串。
返回结果:
- “number” : number
- “string” : string
- “boolean” : boolean
- “object” : array object null
- “function” : function
- “undefined” : undifined
instanceof
instanceof 运算符用来测试一个对象在其原型链中是否存在一个构造函数的 prototype 属性。
var num = 123;
num instanceof Number // false
var Num = new Number(num)
Num instanceof Number // true
Num instanceof Object // true
var str = 'abc'
str instanceof String // false
var Str = new String(str)
Str instanceof String // true
Str instanceof Object // true
var bool = false
bool instanceof Boolean // false
var Bool = new String(bool)
Bool instanceof Boolean // true
Bool instanceof Object // true
var arr = []
arr instanceof Array // true
arr instanceof Object // true
var func = () => {}
func instanceof Function // true
func instanceof Object // true
var obj = {}
obj instanceof Object // true
null instanceof Object // false
实现instanceof
function _instanceof(instance, proto){
const prototype = proto.prototype;
let target = Object.getPrototypeOf(instance);
// 即target = instance.__proto__
while(true){
if(target === prototype ){
return true
}
if(target === null){
return false
}
target = Object.getPrototypeOf(target);
}
}
_instanceof([], Array) // true
Object.prototype.toString.call
Object.prototype指向Object构造函数的原型,通过调用toString方法返回其原型字符串形式的可以显示构建对象的类型。使用要判断类型的变量通过call方法调用此方法(该变量作为对象形式执行)即可显示该变量构建对象的类型。此方法可以相对较全的判断js的数据类型。
Object.prototype.toString.call(true);//[object Boolean]
Object.prototype.toString.call(123);//[object Number]
Object.prototype.toString.call('str');//[object String]
Object.prototype.toString.call();//[object Undefined]
Object.prototype.toString.call(null);//[object Null]
Object.prototype.toString.call([]);//[object Array]
Object.prototype.toString.call({});//[object Object]
Object.prototype.toString.call(function(){});//[object Function]
Object.prototype.toString.call(Symbol()); //[object Symbol]