访问typescript类的成员变量需要' this '吗?



在下面的类中,我使用this9次来处理成员变量和函数。它阻塞了我所有漂亮的代码!我能做点什么让它更漂亮吗?例如,是否可以在不引用this的情况下访问context成员变量?

//controls timing and game phases.
import { Context } from "./helpers/Context"
import { Model } from "./Model"
import { View } from "./View"
export class Controller {
context : Context;
constructor(context : Context) {
this.context = context;
}

//make other objects in context, add them in.
begin = () : void => {
this.context.model = new Model(this.context);
this.context.view = new View(this.context);
this.init();
} 
init = () : void => {
this.context.model.init();
this.context.view.init();
//causes an error! help.
this.context.model.preloadModels([ 
"/models/bleachers.obj"
], () => { this.buildWorld(); })
}
buildWorld = () : void => {
this.context.view.makeGrass();
this.context.view.makeSkybox();
this.context.view.makeBleachersOnEdgeOfField();
}
}

如果您习惯于C或Java等语言,在这些语言中您不必为类字段使用this,那么它一开始可能看起来很奇怪。我也这么想。但是对于像Javascript和Python这样的语言,经常编写thisself是很正常的。我认为这只是一个特定于语言风格的东西,对于不习惯看到它的人来说可能看起来很丑,但这是正常的方式,大多数JS程序员不会认为它是丑陋的,因为他们已经习惯了。

最新更新