当前位置: 代码网 > it编程>编程语言>Javascript > TypeScript判断对象类型的四种方式

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

2024年07月28日 Javascript 我要评论
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>

 

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com