TypeScript判斷對象類型的4種方式代碼
更新時間:2023年07月22日 11:08:54 作者:蒼穹之躍
這篇文章主要給大家介紹了關于TypeScript判斷對象類型的4種方式代碼,TypeScript能根據(jù)一些簡單的規(guī)則推斷(檢查)變量的類型,你可以通過實踐很快的了解它們,需要的朋友可以參考下
一、typeof
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
{} 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){ //循環(huán)判斷對象的原型是否等于類型的原型,直到對象原型為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四、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);
// 指令綁定的參數(shù)
console.log(binding)
// 如果是輸入框
if (el instanceof HTMLInputElement) {
// 元素聚焦
el.focus();
el.placeholder = '請輸入';
el.value = '勤奮、努力'
}else if (el instanceof HTMLAnchorElement) {
// 如果是<a>標簽我們就導向 百度翻譯
el.
}
}
}
</script>
<template>
<input v-focus/>
<p/>
<a v-focus rel="external nofollow" >百度一下,你就知道</a>
</template>
總結(jié)
相關文章
javascript addBookmark 加入收藏 多瀏覽器兼容
不錯的加入收藏代碼,加入了對一些常見瀏覽器的判斷,更好的體現(xiàn)用戶體驗,兼容了ie,firefox.2009-08-08
Bootstrap滾動監(jiān)聽組件scrollspy.js使用方法詳解
這篇文章主要為大家詳細介紹了Bootstrap滾動監(jiān)聽組件scrollspy.js的使用方法,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-07-07
JS pushlet XMLAdapter適配器用法案例解析
這篇文章主要介紹了JS pushlet XMLAdapter適配器用法案例解析,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下2020-10-10
JavaScript中如何通過arguments對象實現(xiàn)對象的重載
js 中不存在函數(shù)的重載,但卻可以通過arguments對象實現(xiàn)對象的重載,下面有個不錯的示例,大家可以參考下2014-05-05
javascript設計模式 – 簡單工廠模式原理與應用實例分析
這篇文章主要介紹了javascript設計模式 – 簡單工廠模式,結(jié)合實例形式分析了javascript簡單工廠模式基本概念、原理、定義、應用場景及操作注意事項,需要的朋友可以參考下2020-04-04
詳解JavaScript中8 種不同的繼承實現(xiàn)方式
在 JavaScript 中,繼承是實現(xiàn)代碼復用和構(gòu)建復雜對象關系的重要機制,雖然 JavaScript 是一門基于原型的語言,不像傳統(tǒng)面向?qū)ο笳Z言那樣有類的概念,但它提供了多種實現(xiàn)繼承的方式,本文將詳細介紹 JavaScript 中 8 種不同的繼承實現(xiàn)方式,需要的朋友可以參考下2025-05-05

