【问题标题】:Defining a variable as a method that was the caller of the method that contains the variable将变量定义为方法,该方法是包含该变量的方法的调用者
【发布时间】:2020-10-24 17:13:53
【问题描述】:

这很难用一个句子作为标题来解释,但基本上我正在处理一个导致错误的 TypeScript 文件。 Here 是一个带有模拟问题的代码的 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

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

谢谢!

【问题讨论】:

  • 您的链接只是到操场,它不是代码共享链接。无论如何,请直接在您的问题中包含 TypeScript。

标签: javascript typescript function methods


【解决方案1】:

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

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

new A().b();

【讨论】:

  • 有没有办法通过调用“d”变量作为函数而不是在“this”上使用访问器来做到这一点?
  • @Tartarus13 如果您想在其中使用this,则不要。 @qxg 提供了一种让它工作的相当老套的方法,但我不鼓励在方法中使用箭头函数。您基本上会滥用该原则来实现将其称为独立变量的奇怪目标。
  • @Tartarus13: const b = this.b.bind(this) / const b = () =&gt; this.b()
【解决方案2】:

一定是dup,不过用箭头函数就行了

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

查看https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions

箭头函数没有自己的 this。使用封闭词法范围的 this 值;

【讨论】:

    【解决方案3】:

    Christian 的答案是 100% 正确的。为您解释:由于Javascript this-binding,此变量将未定义。 例如这里的代码也可以工作:

    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”系列丛书。这是this变量的章节:https://github.com/getify/You-Dont-Know-JS/blob/1st-ed/this%20%26%20object%20prototypes/ch1.md

    【讨论】:

      猜你喜欢
      • 2016-08-27
      • 1970-01-01
      • 2023-03-19
      • 2014-06-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-02
      相关资源
      最近更新 更多