0

I am novice in nodejs and I tried to write a function that gets a function/method as an argument and calling that function/method from inside.

For Example:

function add(a, b) {
    return a + b;   
}

function callingFunc(func) {
    return func(1, 2);
}

callingFunc(add);

But the problem is when I trying to call to a method of an instance from the calling function.

class Example {
    constructor(day) {
        this.day = day;
    }
    
    getDay() {
        return this.day
    }
}

function add(a, b) {
    return a + b;   
}

function callingFunc(func) {
    return func(1, 2);
}

const example = new Example("sunday");
callingFunc(example.getDay);

It returns this error:

/home/cg/root/8845458/main.js:9
        return this.day
                   ^

TypeError: Cannot read property 'day' of undefined
    at getDay (/home/cg/root/8845458/main.js:9:20)
    at callingFunc (/home/cg/root/8845458/main.js:18:12)
    at Object.<anonymous> (/home/cg/root/8845458/main.js:22:1)
    at Module._compile (module.js:570:32)
    at Object.Module._extensions..js (module.js:579:10)
    at Module.load (module.js:487:32)
    at tryModuleLoad (module.js:446:12)
    at Function.Module._load (module.js:438:3)
    at Module.runMain (module.js:604:10)
    at run (bootstrap_node.js:389:7)

1 Answers1

0

You have to bind the right context to the function. Try this:

callingFunc(example.getDay.bind(example));
Dom
  • 734
  • 3
  • 8