【问题标题】:Is `this` necessary to access member variables of typescript classes?访问打字稿类的成员变量是否需要`this`?
【发布时间】: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


【解决方案1】:

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

【讨论】:

  • 好的!可以理解。我写的字好像有一半是this,而且似乎“错了”。
猜你喜欢
  • 2015-12-16
  • 2020-12-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-11-06
  • 2021-12-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多