0

I am currently working on a project where I want to deference an array of functions (function references) and excecute the 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.

Here's my code sample 'working' the same way my original project does: After calling function2 the engine cannot find this.log...

Do you have ideas? Thank you very much in advance.

KR, Robert

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);

3 Answers 3

1

This is an example of Javascript's execution contexts in action. 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:

Example 1: Bind them in the constructor:

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

Example 2: Create them as arrow functions:

class ArrayWithFunctions {

    // ...

    function1 = () => {
        console.log('I am Function 1.');
    }
    
    function2 = () => {
        this.log('I am Function 2.');
    }
}
Sign up to request clarification or add additional context in comments.

Comments

0

You can use arrow functions to dodge scoping issues:

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

Comments

0

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?).

In this case you can simply set the correct this value by calling the function with .call:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.