0

I am trying to call a function via reference. It all starts in callMe() of class DynamicCalls:

interface IDynamicFunction {
    name: string;
    func: (param: string) => void;
}

class DynamicCalls {

    private dynamicCall: IDynamicFunction = { name: "myDynamic", func: this.testFunc };

    public callMe() {
        this.callFromDynamic("Works"); // 1st -> Works
        this.testFunc("Works, also"); // 2nd -> Works
        this.dynamicCall.func("First Call"); // 3rd -> Error: callFromDynamic seems to be unknown in testFunc
    }

    private callFromDynamic(param: string): void {
        console.log("Param: " + param);
    }

    private testFunc(param: string): void {
        console.log("Param: " + param);
        this.callFromDynamic("Second call"); // Gives error -> TypeError: this.callFromDynamic is not a function
    }
}

let dynamicCalls: DynamicCalls = new DynamicCalls();

dynamicCalls.callMe();

I expect that the 3rd call (this.dynamicCall.func("First Call");) works like this.testFunc("Works, also").

Can anyone explain to me why I get this TypeError: this.callFromDynamic is not a function? And how I can avoid it?

Thanks a lot in advance.

Kind regards, Okean

2 Answers 2

2

The problem is that you lose the context.

In your case, this refers to the same object: {name: string, func: Function}

So you could work with:

private dynamicCall: IDynamicFunction = {
  name: "myDynamic",
  anotherFun: () => console.log('another func'),
  func: this.anotherFun()
};

Try:

private dynamicCall: IDynamicFunction = {
  name: "myDynamic",
  func: (param: string) => this.testFunc(param)
};
Sign up to request clarification or add additional context in comments.

Comments

0

@MaximP is right, but there is another solution.

    private callFromDynamic = (param: string): void => {
        console.log("Param: " + param);
    };

    private testFunc = (param: string): void => {
        console.log("Param: " + param);
        this.callFromDynamic("Second call");
    };

Change your functions to fields, now they'll keep their context without need to wrap their calls.

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.