判断对象类型的三种方法

22 篇文章 0 订阅

//A instanceof B
//判断A对象是不是B构造出来的
//判断A对象的原型链上有木有B
   
   function Person(){}
   var person=new Person();
   var obj={};
   console.log(person instanceof Person);//true
   console.log(person instanceof Object);//true
   console.log(obj instanceof Person);//false
   console.log([] instanceof Array);//true 


   //判断输入的arr是数组还是对象
   //三种方法
   var arr=[]||{};
   1.arr.constructor  
   console.log([].constructor);//function Array(){}
   var obj={}
   console.log(obj.constructor);//function Object(){}


   2.[] instanceof Array //true
     obj instanceof Object//true


   3.Object.prototype.toString.call()方法
     Object.prototype.toString=function(){
      第一识别this
      返回相应的结果
        使用call来改变this指向

     }

 

 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在TypeScript中,可以使用类型断言和类型保护来判断对象类型。 1. 类型断言(Type Assertion): 类型断言是一种告诉编译器某个值的具体类型的方式。可以使用尖括号语法或者as关键字进行类型断言。 例如: ```typescript let obj: any = "hello"; let strLength: number = (<string>obj).length; // 使用尖括号语法进行类型断言 let strLength: number = (obj as string).length; // 使用as关键字进行类型断言 ``` 2. 类型保护(Type Guard): 类型保护是一种在特定范围内缩小变量的类型的方式,以便在该范围内使用特定类型的属性和方法。 TypeScript提供了多种类型保护的方式,包括typeof类型保护、instanceof类型保护和自定义类型保护。 - typeof类型保护: 可以使用typeof操作符来判断基本类型的变量类型。 例如: ```typescript function printLength(obj: string | number) { if (typeof obj === "string") { console.log(obj.length); // 在这个范围内,obj被缩小为string类型 } else { console.log(obj); // 在这个范围内,obj被缩小为number类型 } } ``` - instanceof类型保护: 可以使用instanceof操作符来判断对象的具体类型。 例如: ```typescript class Animal { name: string; constructor(name: string) { this.name = name; } } class Dog extends Animal { breed: string; constructor(name: string, breed: string) { super(name); this.breed = breed; } } function printName(animal: Animal) { if (animal instanceof Dog) { console.log(animal.breed); // 在这个范围内,animal被缩小为Dog类型 } else { console.log(animal.name); // 在这个范围内,animal被缩小为Animal类型 } } ``` - 自定义类型保护: 可以使用自定义的类型保护函数来判断对象的具体类型。 例如: ```typescript function isString(obj: any): obj is string { return typeof obj === "string"; } function printLength(obj: string | number) { if (isString(obj)) { console.log(obj.length); // 在这个范围内,obj被缩小为string类型 } else { console.log(obj); // 在这个范围内,obj被缩小为number类型 } } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值