首页 > 解决方案 > 访问打字稿类的成员变量是否需要`this`?

问题描述

在下面的类中,我使用了this9 次来处理成员变量和函数。它阻塞了我所有漂亮的代码!有什么我可以做的让它更漂亮吗?例如,无论如何都可以在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();
    }

}

标签: javascripttypescriptbindingthis

解决方案


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


推荐阅读