Typescript,为什么只有一些属性是可访问的?
我正在尝试用打字脚本做一些基本的东西。我已经声明了这样一个类。因为我想使用类的成员属性,所以我不想在nameChanged函数中使用this关键字Typescript,为什么只有一些属性是可访问的?,typescript,Typescript,我正在尝试用打字脚本做一些基本的东西。我已经声明了这样一个类。因为我想使用类的成员属性,所以我不想在nameChanged函数中使用this关键字 class testController { constructor() { } reaction:string = "trist"; name:string = "erik"; showReaction:boolean = false;
class testController {
constructor()
{
}
reaction:string = "trist";
name:string = "erik";
showReaction:boolean = false;
nameChanged()
{
if(name=="olle")
{
this.reaction = "Yippie";
this.showReaction = true;
}
else { this.showReaction = false; }
}
}
如果我写这行
this.reaction = "Yippie";
去掉“this”键,我会得到一个编译错误。找不到符号“反应”。
showReaction属性也是如此,但name的行为与预期的一样
我错过什么了吗?如何使reaction和showReaction的行为类似于name?访问name并不是指类成员名称。您实际上正在访问全局名称变量。您只能使用this关键字访问类成员。与JavaScript一样,TypeScript需要
this
上下文来建立“where”来定位对象上的函数和属性。没有它,一切都将是全局的(更准确地说,它将在范围链中搜索所请求的变量声明)。而且,在TypeScript中,编译器将捕获尝试使用全局变量但未定义的实例
与其他一些语言(如C#)不同,类的实例方法中没有默认上下文(由用法决定的隐式this
)。当您想要引用实例方法和属性时,需要显式地使用this
如果name
在不使用this.name
的情况下工作,则意味着在您的类上定义的函数上下文之外的其他地方定义了一个全局name
。例如,它可能是这样的:
var name: string="global";
class Test {
name: string;
public helloName():string {
return "hello " + name;
}
}
var t = new Test();
t.name = "instance";
var result = t.helloName(); // result = "hello global"
如果函数体被修改为引用此.name
:
return "hello " + this.name;
产出将是:
var result = t.helloName(); // result = "hello instance"