[英]Why 'this' is not allowed on the left side of assignment
In the component class i have been writing this: 在组件类中,我一直在这样写:
export class myapp{
detail;
myarr = ['me', 'myself', 'i'];
title = this.myarr[0];
this.detail = this.title ; //error
}
why this.detail is not allowed but this.title is allowed, why I have to create new variable, cant I use variable already in the class 为什么不允许this.detail但允许this.title,为什么我必须创建新变量,不能在类中使用变量
Inside a class but outside of methods you can only initialize fields or declare methods. 在类内部但方法之外,您只能初始化字段或声明方法。 You can't add arbitrary statements there.
您不能在那里添加任意语句。
You can use the constructor()
for that 您可以使用
constructor()
export class myapp{
detail : string = 'I am';
myarr = ['me', 'myself', 'i'];
title = this.myarr[0];
constructor() {
this.detail = this.title ;
}
}
In your instance, there is no point re-declaring the class member... 在您的实例中,没有必要重新声明类成员。
export class myapp{
myarr = ['me', 'myself', 'i'];
title = this.myarr[0];
detail = this.title ;
}
Why is TypeScript doing this? 为什么TypeScript这样做?
TypeScript is helping you to spot that you may have accidentally declared a second member with the same name by stopping you from doing what you are attempting. TypeScript通过阻止您执行正在尝试的操作,来帮助您发现您不小心声明了另一个具有相同名称的成员。
You will also note that you don't need to use the this
prefix for members in a class. 您还将注意到,您无需为类中的成员使用
this
前缀。 The generated JavaScript will have them... 生成的JavaScript将具有它们...
var myapp = (function () {
function myapp() {
this.myarr = ['me', 'myself', 'i'];
this.title = this.myarr[0];
this.detail = this.title;
}
return myapp;
}());
You can prefix the members with an access modifier. 您可以在成员前面加上访问修饰符。 They are private by default.
默认情况下,它们是私有的。
export class myapp{
private myarr = ['me', 'myself', 'i'];
protected title = this.myarr[0];
public detail = this.title ;
}
Access modifiers are enforced at compile time only. 访问修饰符仅在编译时强制执行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.