typescript中this报错的解决
目录
- typescript中this报错
- 出错原因
- 改成这样就可以了
- typescript中this的使用注意
- 总结
tyPEscript中this报错
export class Appcomponent {
tITle = 'myapp';
count=1;
clickme=function(){
this.count++;
}
在上述代码中
使用this报错: 'this' implicitly has type 'any' because it does not have a type annotation.
function处报错: An outer value of 'this' is shadowed by this container
出错原因
ts 提供类似C# 和 java的静态类型(强类型), 在全局和命名空间的全局里面 直接声明一个函数要用到 function 关键字(就是js的function关键字),
而在类(class)里面却不能使用function来声明方法。
这其中是this的指向问题。
改成这样就可以了
export class AppComponent {
title = 'myapp';
count=1;
clickme=()=>
{
this.count++;
}
}
typescript中this的使用注意
最近的一个项目,用了 typescript 来写js脚本,结果错误百出,修复的同时也让我总结了ts 中该怎样使用this。
ts 提供类似C# 和 java的静态类型(强类型), 在全局和命名空间的全局里面 直接声明一个函数 要用到 function 关键字(就是js的function关键字),而在类(class)里面却不能使用function来声明方法。
让我们来比较 它与 C# 的不同
public delegate int handle();
public class PRogram {
public static void Main(string[] args) {
VAR t = new test();
var a = new A();
t.h = a.hander;
t.count = t.h();
Console.WriteLine("count is:{
0}
",t.count);
// output: // count is:1 }
}
public class Test {
public handle h;
public int count = 100;
}
public class A {
private int count = 0;
public int hander() {
this.count +=1;
return this.count;
}
}
这个代码在class A里面 放了一个方法,并将这个方法作为一个委托 给了 class program 的 h 字段, 最后在 Main 方法里面运个 h委托, 结果得到了 1 这个结果(A.count + 1 = 0 + 1 = 1)
让我们在TypeScript 里面实现相同的功能:
class A {
public count: number = 0;
public hander(): number {
this.count += 1;
return this.count;
}
}
class Test {
public count: number = 100;
public h: () =>
number;
}
class Program {
static Main(): void {
let t = new Test();
let a = new A();
t.h = a.hander;
t.count = t.h();
console.LOG(`count is :${
t.count}
`);
// output // count is :101 }
}
Program.Main();
// 为了跟C#一致 , 提供的静态入口你会发现,这时候结果不再是1,而是101, 造成差异的原因是js的 this 指针 , 在 C# 中 this 总是指向当前的类,而 js中的this可以改变, 当 t.h = a.hander 的时候 t.h 中的this 变成了 Test 类。 而在 typescript中,因为当前定义的是一个类,所以其this 总是指向 类,所以TS 直接使用js中的this.
然而 有办法解决这个问题么? 当然有。 让我们来改变 class A
class A {
constructor() {
this.hander = ()=>
{
this.count += 1;
return this.count;
}
}
public count: number = 0;
public hander: () =>
number;
}
这样我们把hander 从类的 方法 变成了 类的变量,更重要的是 我们在 构造函数里面 使用 lamda 表达式 , 使用 lamda表达式 并不会改变this的作用域, 因为当前是一个构造函数,所以里面的this指向的是 当前的类,(查看一下生成的js会更容易理解, 函数里面已经没有了this)
从js的角度, 因为函数中没有了this指针,所以也就不会因为 传递到其他的地方造成不一致的情况
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持。
您可能感兴趣的文章:- Vue+Typescript中在Vue上挂载axios使用时报错问题
- 详解在Vue中使用TypeScript的一些思考(实践)
- 关于Vue新搭档TypeScript快速入门实践
声明:本文内容由网友自发贡献,本站不承担相应法律责任。对本内容有异议或投诉,请联系2913721942#qq.com核实处理,我们将尽快回复您,谢谢合作!
若转载请注明出处: typescript中this报错的解决
本文地址: https://pptw.com/jishu/609397.html
