![](/img/trans.png)
[英]Why void functions are allowed in left part of assignment in Typescript?
[英]Why 'this' is not allowed on the left side of assignment
在组件类中,我一直在这样写:
export class myapp{
detail;
myarr = ['me', 'myself', 'i'];
title = this.myarr[0];
this.detail = this.title ; //error
}
为什么不允许this.detail但允许this.title,为什么我必须创建新变量,不能在类中使用变量
在类内部但方法之外,您只能初始化字段或声明方法。 您不能在那里添加任意语句。
您可以使用constructor()
export class myapp{
detail : string = 'I am';
myarr = ['me', 'myself', 'i'];
title = this.myarr[0];
constructor() {
this.detail = this.title ;
}
}
在您的实例中,没有必要重新声明类成员。
export class myapp{
myarr = ['me', 'myself', 'i'];
title = this.myarr[0];
detail = this.title ;
}
为什么TypeScript这样做?
TypeScript通过阻止您执行正在尝试的操作,来帮助您发现您不小心声明了另一个具有相同名称的成员。
您还将注意到,您无需为类中的成员使用this
前缀。 生成的JavaScript将具有它们...
var myapp = (function () {
function myapp() {
this.myarr = ['me', 'myself', 'i'];
this.title = this.myarr[0];
this.detail = this.title;
}
return myapp;
}());
您可以在成员前面加上访问修饰符。 默认情况下,它们是私有的。
export class myapp{
private myarr = ['me', 'myself', 'i'];
protected title = this.myarr[0];
public detail = this.title ;
}
访问修饰符仅在编译时强制执行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.