typeof是一个操做符,其右侧跟一个一元表达式,并返回这个表达式的数据类型。返回的结果用该类型的字符串(全小写字母)形式表示,包括number,string,boolean,undefined,object,function,symbol等。app
typeof ""; //string
typeof 1; //number
typeof false; //boolean
typeof undefined; //undefined
typeof function(){}; //function
typeof {}; //object
typeof Symbol(); //symbol
typeof null; //object
typeof []; //object
typeof new Date(); //object
typeof new RegExp(); //object
instanceof用来判断A是否为B的实例,表达式为:A instanceof B,若是A是B的实例,则返回true,不然返回false。instanceof检测的是原型,内部机制是经过判断对象的原型链中是否有类型的原型。函数
{} instanceof Object; //true
[] instanceof Array; //true
[] instanceof Object; //true
"123" instanceof String; //false
new String(123) instanceof String; //true
咱们能够用下面的代码实现instanceof。spa
function instance(left,right){ let prototype = right.prototype; //获取类型的原型
let proto = left.__proto__; //获取对象的原型
while(true){ //循环判断对象的原型是否等于类型的原型,直到对象原型为null,由于原型链最终为null
if (proto === null || proto === undefined){ return false; } if (proto === prototype){ return true; } proto = proto.__proto__; } } console.log(instance({},Object)); //true
console.log(instance([],Number)); //false
当一个函数F被定义时,JS引擎会为F添加prototype原型,而后在prototype上添加一个constructor属性,并让其指向F的引用,F利用原型对象的constructor属性引用了自身,当F做为构造函数建立对象时,原型上的constructor属性被遗传到了新建立的对象上,从原型链角度讲,构造函数F就是新对象的类型。这样作的意义是,让对象诞生之后,就具备可追溯的数据类型。prototype
toString()是Object的原型方法,调用该方法,默认返回当前对象的[[Class]]。这是一个内部属性,其格式为[object Xxx],其中Xxx就是对象的类型。code
对于Object对象,直接调用toString()就能返回[object Object],而对于其余对象,则须要经过call、apply来调用才能返回正确的类型信息。对象
function getType(obj){ let type = typeof obj; if(type != "object"){ return type; } return Object.prototype.toString.call(obj).replace(/^\[object (\S+)\]$/, '$1'); }