【发布时间】:2021-11-10 19:25:26
【问题描述】:
在下面的类中,我使用this 9次来处理成员变量和函数。它阻塞了我所有漂亮的代码!有什么我可以做的让它更漂亮吗?比如有没有不引用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();
}
}
【问题讨论】:
-
一种方法是使用工厂函数而不是类,但我不知道这是否适合您。
-
@ShamPooSham。有趣的!告诉我更多?
-
它看起来有点奇怪,但本质上你创建了一个函数而不是一个类,并且你使用闭包函数而不是其中的实例方法。看看这个中等帖子。 medium.com/programming-essentials/…
标签: javascript typescript binding this