首页 > 解决方案 > 将变量定义为一个方法,该方法是包含该变量的方法的调用者

问题描述

这很难用一个句子作为标题来解释,但基本上我正在处理一个导致错误的 TypeScript 文件。是一个带有模拟问题代码的 TypeScript 游乐场;JS中的代码与TS中的代码基本相同。

这是 TS 操场外的代码:

const A = (class A {
    b() {
        const d = this.d;
        d();
    }
    d() {
        const b = this.b;
    }
})
new A().b()

这是错误:

Uncaught TypeError: Cannot read property 'b' of undefined
    at d (eval at <anonymous> (main-3.js:1241), <anonymous>:8:24)
    at A.b (eval at <anonymous> (main-3.js:1241), <anonymous>:5:9)
    at eval (eval at <anonymous> (main-3.js:1241), <anonymous>:11:9)
    at main-3.js:1241

在维护变量声明别名的同时如何避免这种情况的任何帮助都会很有用。

谢谢!

标签: javascripttypescriptfunctionmethods

解决方案


调用该d()方法,this.d()并将this在该方法中定义:

const A = class {
    b() {
        const d = this.d;
        this.d();
    }
    d() {
        const b = this.b;
        console.log(b);
    }
};

new A().b();


推荐阅读