一、typeof

typeof "";//stringtypeof 1; //numbertypeof false; //booleantypeof undefined; //undefinedtypeof function(){}; //functiontypeof {}; //objecttypeof Symbol(); //symboltypeof null; //objecttypeof []; //objecttypeof new Date(); //objecttypeof new RegExp(); //object

二、instanceof

{} instanceof Object; //true[] instanceof Array;//true[] instanceof Object; //true"123" instanceof String; //falsenew String(123) instanceof String; //true

三、constructor

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)); //trueconsole.log(instance([],Number)); //false

四、Object.prototype.toString()

function getType(obj){let type= typeof obj;if(type != "object"){return type;}return Object.prototype.toString.call(obj).replace(/^\[object (\S+)\]$/, '$1');}

使用案例:

const vFocus = {mounted: (el: HTMLElement, binding: any) => {// 指令绑定的元素console.log(typeof el);console.log(el);// 指令绑定的参数console.log(binding)// 如果是输入框if (el instanceof HTMLInputElement) {// 元素聚焦el.focus();el.placeholder = '请输入';el.value = '勤奋、努力'}else if (el instanceof HTMLAnchorElement) {// 如果是标签我们就导向 百度翻译el.href='https://fanyi.baidu.com/'}}}

百度一下,你就知道