You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

TypeScript类访问成员变量是否必须用this?如何省略this优化代码?

减少this使用的几种可行方案

方案1:方法内解构context(无侵入改量最小)

只需在每个方法开头将context从this中解构出来,后续整个方法内都可以直接使用context变量,无需重复写this.context,逻辑和原有代码完全一致,无额外副作用。
修改后的代码如下:

// 控制时序和游戏阶段
import { Context } from "./helpers/Context"
import { Model } from "./Model"
import { View } from "./View"

export class Controller {
    context: Context;

    constructor(context: Context) {
        this.context = context;
    }
    
    // 创建上下文内的其他对象并注入
    begin = (): void => {
        const { context } = this;
        context.model = new Model(context);
        context.view = new View(context);
        this.init();
    } 

    init = (): void => {
        const { context } = this;
        context.model.init();
        context.view.init();

        context.model.preloadModels([ 
            "/models/bleachers.obj"
        ], () => { this.buildWorld(); })
    }

    buildWorld = (): void => {
        const { context } = this;
        context.view.makeGrass();
        context.view.makeSkybox();
        context.view.makeBleachersOnEdgeOfField();
    }
}

方案2:嵌套解构进一步简化

如果觉得context.model/context.view的写法还是繁琐,可以直接解构出context下的属性,进一步减少重复代码:

init = (): void => {
    const { model, view } = this.context;
    model.init();
    view.init();
    model.preloadModels([ 
        "/models/bleachers.obj"
    ], () => { this.buildWorld(); })
}

方案3:抽离为类一级字段(彻底简化调用)

如果model和view是你常用的属性,可以直接定义为类的一级字段,初始化后直接通过this调用,无需再通过context中转:

export class Controller {
    context: Context;
    model: Model;
    view: View;

    constructor(context: Context) {
        this.context = context;
    }
    
    begin = (): void => {
        this.model = new Model(this.context);
        this.view = new View(this.context);
        this.init();
    } 

    init = (): void => {
        this.model.init();
        this.view.init();
        this.model.preloadModels([ 
            "/models/bleachers.obj"
        ], () => { this.buildWorld(); })
    }

    buildWorld = (): void => {
        this.view.makeGrass();
        this.view.makeSkybox();
        this.view.makeBleachersOnEdgeOfField();
    }
}

另外你代码中标记的报错问题:你当前用箭头函数定义类方法,this绑定是稳定的,回调里的this.buildWorld()不会出现指向错误,可优先检查preloadModels的回调参数要求,或者是否在model未完成初始化时就调用了该方法。

内容的提问来源于stack exchange,提问作者Catlard

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 19:54:03