一、typeof
| typeof ""; |
| typeof 1; |
| typeof false; |
| typeof undefined; |
| typeof function(){}; |
| typeof {}; |
| typeof Symbol(); |
| typeof null; |
| typeof []; |
| typeof new Date(); |
| typeof new RegExp(); |
复制
二、instanceof
| {} instanceof Object; |
| [] instanceof Array; |
| [] instanceof Object; |
| "123" instanceof String; |
复制
三、constructor
| function instance(left,right){ |
| let prototype = right.prototype; |
| let proto = left.__proto__; |
| while(true){ |
| if (proto === null || proto === undefined){ |
| return false; |
| } |
| if (proto === prototype){ |
| return true; |
| } |
| proto = proto.__proto__; |
| } |
| } |
| console.log(instance({},Object)); |
| console.log(instance([],Number)); |
复制
四、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'); |
| } |
复制
使用案例:
| <!--src/App.vue--> |
| <script setup lang="ts"> |
| |
| 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/' |
| } |
| } |
| } |
| </script> |
| |
| <template> |
| <input v-focus/> |
| <p/> |
| <a v-focus href="https://www.baidu.com/">百度一下,你就知道</a> |
| </template> |
| |
复制
