当前位置:首页 >> 跨学科知识体系 >> 【TypeScript】this指向,this内置组件,三星i9268怎么样(三星this is)

【TypeScript】this指向,this内置组件,三星i9268怎么样(三星this is)

cpugpu芯片开发光刻机 跨学科知识体系 1
文件名:【TypeScript】this指向,this内置组件,三星i9268怎么样 【TypeScript】this指向,this内置组件

this类型 TypeScript可推导的this类型函数中this默认类型对象中的函数中的this明确this指向 怎么指定this类型 this相关的内置工具类型转换ThisParameterType<>ThisParameterType<>ThisType

TypeScript可推导的this类型 函数中this默认类型 对象中的函数中的this // 对象中的thisconst obj ={a:1,b:2,fun:function(){//默认情况下,this是any类型console.log(this.a)}}obj.fun()//1 明确this指向 步骤1:tsc --init,生成文件 步骤二,打开注释不让有模糊的this,必须指定this指向 this就会更严格,这个是this根据上下文自行推导出来的类型 这个是没有上下文。推导不出来的,在严格模式下,不允许模糊this,所以会报错 怎么指定this类型 函数的第一个参数我们可以根据该函数之后被调用的情况,用于声明this的类型,名词必须叫this在后续调用函数传入参数的时候。从第二个参数开始传递,this参数会在编译后被抹除 // - 把this作为函数的第一个参数,给指定类型function fun( this:{name:string},info:{name:string}){console.log(this)//{ name: '名字' }}//调用的时候,得这样调用,不然会报void类型的错误fun.call({name:"名字"},{name:"第二个名字"}) this相关的内置工具 类型转换 TS提供了一些工具来辅助进行常见的类型转换,这些类型全局可用 ThisParameterType<> 用于提取一个函数类型Type的this没有this,则返回unknown ThisParameterType<> 想要移除一个函数类型type的this参数类型,并且返回当前的函数类型 function fun( this:{name:string},info:{name:string}){console.log(this)}//获取函数的类型type funtype = typeof fun//想要直接获取函数的this类型,采用内置组件type thisType= ThisParameterType<funtype>//想要移除一个函数类型type的this参数类型,并且返回当前剩余的函数类型type thisRemove= OmitThisParameter<funtype>export{} ThisType 被用作标记一个上下文的this类型原始方法 //原始获取this,繁琐type User = {name: stringage: number}type Intype = {User: Usergetname: () => voidgetage: () => void}const username: Intype = {User: {name: "乞力马扎罗",age: 18},//ts接收指定的this指向getname: function (this:User) {console.log(this.name)//乞力马扎罗},getage: function (this:User) {console.log(this.age)//18}}//call() 可以修改函数调用时 this 的指向,其余参数则会作为原函数的参数。//第一个参数 thisArg。代表 this 将会被指向的值。如果不是对象,也会通过 Object() 方法转换为对象。如果是 null 或 undefined,this 则会指向全局对象(即 window 或 global)//传入this指向username.getname.call(username.User)username.getage.call(username.User)export { } 采取ThisType<> type User = {name: stringage: number}type Intype = {User: Usergetname: () => voidgetage: () => void}//通过ThisType<User>,将这里以后不管多少函数,this的指向始终是Userconst username: Intype & ThisType<User> = {User: {name: "乞力马扎罗",age: 18},//ts接收指定的this指向getname: function () {console.log(this.name)//乞力马扎罗},getage: function () {console.log(this.age)//18}}//call() 可以修改函数调用时 this 的指向,其余参数则会作为原函数的参数。//第一个参数 thisArg。代表 this 将会被指向的值。如果不是对象,也会通过 Object() 方法转换为对象。如果是 null 或 undefined,this 则会指向全局对象(即 window 或 global)//传入this指向username.getname.call(username.User)username.getage.call(username.User)export { }
协助本站SEO优化一下,谢谢!
关键词不能为空
同类推荐
«    2025年12月    »
1234567
891011121314
15161718192021
22232425262728
293031
控制面板
您好,欢迎到访网站!
  查看权限
网站分类
搜索
最新留言
文章归档
网站收藏
友情链接