Javascript 将变量定义为包含该变量的方法的调用方的方法

Javascript 将变量定义为包含该变量的方法的调用方的方法,javascript,typescript,function,methods,Javascript,Typescript,Function,Methods,这很难用一句话作为标题来解释,但基本上我正在处理一个导致错误的TypeScript文件。是一个用代码模拟问题的类型脚本;JS中的代码与TS中的代码基本相同 以下是TS游乐场外的代码: const A = (class A { b() { const d = this.d; d(); } d() { const b = this.b; } }) new A().b() 以下是错误: Uncaught TypeErro

这很难用一句话作为标题来解释,但基本上我正在处理一个导致错误的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
Uncaught TypeError:无法读取未定义的属性“b”
在d点(评估点(main-3.js:1241),:8:24)
在A.b(评估在(main-3.js:1241),:5:9)
评估时(评估时)(main-3.js:1241),:11:9)
在main-3。js:1241
关于如何在维护变量声明别名的同时避免这种情况的任何帮助都是有用的

谢谢大家!

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

const A=class{
b(){
const d=这个.d;
这个;
}
d(){
常数b=这个.b;
控制台日志(b);
}
};

新的A().b()它必须是dup,但只需使用箭头功能即可

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

箭头函数对此没有自己的定义。使用封闭词法范围的此值


克里斯蒂安的答案是100%正确的。解释:由于
Javascript此绑定
,此变量将未定义。 例如,此代码也可以用于:

const A = class {
b() {
    const d = this.d;
    d.call(this); // Here we bind the this variable to the Class itself.
}
d() {
    const b = this.b;
    console.log("HERE WE GO!");
}
};

new A().b();

作为对您的推荐,请查看“您不知道JS”系列丛书。以下是
这个
变量的章节:

你的链接只是到游乐场,而不是代码共享链接。无论如何,请直接在您的问题中包含类型脚本。有没有办法通过调用“d”变量作为函数而不是在“this”上使用访问器来实现这一点?@Tartarus13如果您想在其中使用
this
@qxg提供了一种相当简陋的工作方式,但我不鼓励在方法中使用箭头函数。您基本上是在滥用该原则,只是为了实现将其作为独立变量调用的奇怪目标。@Tartarus13:
const b=this.b.bind(this)
/
const b=()=>this.b()