【问题标题】:JavaScript class methods in an array or object数组或对象中的 JavaScript 类方法
【发布时间】:2021-11-30 01:03:17
【问题描述】:

我目前正在从事一个项目,我想在其中尊重一组函数(函数引用)并执行该函数。

这只有在我不在函数中调用另一个类方法时才有效。 否则我会得到“Uncaught TypeError”,我不知道如何解决这个错误。

这是我的代码示例“工作”的方式与我的原始项目相同: 调用function2后引擎找不到this.log...

你有想法吗?非常感谢您。

KR,罗伯特

class ArrayWithFunctions {

    constructor() {
        this.functionTable = [
            this.function1,
            this.function2,
        ];
        
    }
    
    execute(index) {
        return (this.functionTable[index])();
    }
    
    log(chars) {
        console.log(chars);
    }
    
    function1() {
        console.log('I am Function 1.');
    }
    
    function2() {
        this.log('I am Function 2.');
    }
}

let example = new ArrayWithFunctions();
example.execute(0);
example.execute(1);

【问题讨论】:

    标签: javascript arrays function


    【解决方案1】:

    这是 Javascript 执行上下文的示例。在这种情况下,为避免丢失对类的正确引用,可以在将函数放入数组时进行绑定,或者将它们初始化为箭头函数:

    示例1:在构造函数中绑定:

        constructor() {
            this.functionTable = [
                this.function1.bind(this),
                this.function2.bind(this),
            ];
            
        }
    

    示例 2:将它们创建为箭头函数:

    class ArrayWithFunctions {
    
        // ...
    
        function1 = () => {
            console.log('I am Function 1.');
        }
        
        function2 = () => {
            this.log('I am Function 2.');
        }
    }
    

    【讨论】:

      【解决方案2】:

      相关:How to access the correct `this` inside a callback(您可能还想看看How does the "this" keyword work?)。

      在这种情况下,您可以通过使用.call 调用函数来简单地设置正确的this 值:

      return this.functionTable[index].call(this);
      

      【讨论】:

        【解决方案3】:

        您可以使用箭头函数来规避范围问题:

        function2 = () => {
             this.log('I am function 2.');
        }
        

        【讨论】:

          猜你喜欢
          • 2020-01-05
          • 1970-01-01
          • 2017-10-24
          • 2011-09-29
          • 1970-01-01
          • 1970-01-01
          • 2021-03-04
          • 2011-12-09
          • 1970-01-01
          相关资源
          最近更新 更多