javascript - 访问打字稿类的成员变量是否需要`this`?
问题描述
在下面的类中,我使用了this
9 次来处理成员变量和函数。它阻塞了我所有漂亮的代码!有什么我可以做的让它更漂亮吗?例如,无论如何都可以在context
不引用的情况下访问成员变量this
?
//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();
}
}
解决方案
如果您习惯于不必使用this
类字段的 C 或 Java 等语言,那么一开始它可能看起来很奇怪。我也有同样的想法。this
但是对于像 Javascript 和 Python 这样的语言,写self
很多次是很正常的。我认为这只是一种特定于语言的样式,对于不习惯看到它的人来说可能看起来很丑,但这是正常的方式,大多数 JS 程序员不会认为它很丑,因为他们已经习惯了。
推荐阅读
- c++ - Apply Blur effect to a ID3D11Texture2D
- javascript - 基于 2 个变量的 JavaScript 表单重定向
- correlation - 如何获取列之间的相关性,发现最相关的列并将它们绘制在热图中?
- python - Python 从现在开始获取年初至今
- r - R:使用类似于 cumsum(折旧)的前一行(=滞后)的迭代更新值创建变量
- python - 如何在python中提取字符串的一部分?
- javascript - 使元素随着鼠标移动而移动
- css - 在 weasyprint 中不知道其编号的情况下样式化 pdf 页面
- linux - 如何使用 IF 测试一个值是否满足某个掩码
- rust - 创建引用错误的递归列表“由于要求冲突,无法推断 autoref 的适当生命周期”