简体   繁体   English

JavaScript class 数组中的方法或 object

[英]JavaScript class methods in an array or object

I am currently working on a project where I want to deference an array of functions (function references) and excecute the function.我目前正在做一个项目,我想在其中引用一组函数(函数引用)并执行 function。

This does only work, if I don't call another class method within the function. Otherwise I get "Uncaught TypeError" and I can't figure out how to solve this error.这仅在我不调用 function 中的另一个 class 方法时才有效。否则我会得到“Uncaught TypeError”并且我不知道如何解决这个错误。

Here's my code sample 'working' the same way my original project does: After calling function2 the engine cannot find this.log...这是我的代码示例以与我的原始项目相同的方式“工作”:调用 function2 后引擎找不到 this.log ...

Do you have ideas?你有想法吗? Thank you very much in advance.非常感谢你提前。

KR, Robert 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);

This is an example of Javascript's execution contexts in action.这是 Javascript 执行上下文的一个例子。 In this situation, to avoid losing the correct reference to the class, you can bind the functions when putting them inside the array, or initialize them as arrow functions:在这种情况下,为了避免丢失对 class 的正确引用,可以在将函数放入数组时绑定它们,或者将它们初始化为箭头函数:

Example 1: Bind them in the constructor:示例 1:在构造函数中绑定它们:

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

Example 2: Create them as arrow functions:示例 2:将它们创建为箭头函数:

class ArrayWithFunctions {

    // ...

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

You can use arrow functions to dodge scoping issues:您可以使用箭头函数来避免作用域问题:

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

Related: How to access the correct `this` inside a callback (and you might also want to take a look at How does the "this" keyword work? ).相关: How to access the correct `this` inside a callback (您可能还想看看“this”关键字如何工作? )。

In this case you can simply set the correct this value by calling the function with .call :在这种情况下,您可以通过使用.call调用 function 来简单地设置正确的this值:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM