Object.prototype.toString.call(‘hello‘); // "[object String]"
Object.prototype.toString.call({name:‘jack‘}); // "[object Object]"
typeof ‘hello‘ //"string"
typeof({}) //"object"
typeof null //"object"
function a(){}
a instanceof Object // true
null instanceof Object //false
"a" instanceof String //false
typeof:利用Object.prototype.toString.call()返回值进行字符串切割来实现
function myTypeof(arg){
let typeStr = Object.prototype.toString.call(arg);
return typeStr.split(‘ ‘)[1].split(‘]‘)[0].toLowerCase();
}
instanceof:通过便利原型链来比较实现
function myInstanceof(instance,type){
while(instance){
instance=instance.__proto__;
if(instance===type.prototype) return true;
}
return false
}
原文:https://www.cnblogs.com/xingguozhiming/p/14091227.html