TypeScript判断对象类型的四种方式

一、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){    //循环判断对象的原型是否等于类型的原型,直到对象原型为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);
    // 指令绑定的参数
    console.log(binding)

    // 如果是输入框
    if (el instanceof HTMLInputElement) {
      // 元素聚焦
      el.focus();
      el.placeholder = '请输入';
      el.value = '勤奋、努力'
    }else if (el instanceof HTMLAnchorElement) {
      // 如果是<a>标签我们就导向 百度翻译
      el.href='https://fanyi.baidu.com/'
    }
  }
}
</script>

<template>
  <input v-focus/>
  <p/>
  <a v-focus href="https://www.baidu.com/">百度一下,你就知道</a>
</template>

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

文子阳

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值