0

Consider the following code snippet.

function outsiderFunction(opt){
    opt.helperMethod();
}

class SomeClass {
    constructor(options) {
        this.options = options;
    }
    update() {
        outsiderFunction({
            helperMethod: this.help
        })
    }
    help() {
        this.helpUtil();
    }
    helpUtil() {
        console.log('help util')
    }
}
const x = new SomeClass();
x.update();

The update function of SomeClass calls the outsiderFunction passing the helperMethod as one of the functions (help) of the same class.

But now the help function also needs to call one of the functions of that class named helpUtil but since it was called by an outsider function the this reference refers to outsider function and not the class.

Note: I can not bring outsider function inside the class

One workaround kind of thing that I did is as shown below:

function outsiderFunction(opt){
    opt.helperMethod();
}

class SomeClass {
    constructor(options) {
        this.options = options;
    }
    update() {
        outsiderFunction({
            helperMethod: this.help,
            ReferenceClass: this
        })
    }
    help() {
        let that  = this.ReferenceClass;
        that.helpUtil();
    }
    helpUtil() {
        console.log('help util')
    }
}
const x = new SomeClass();
x.update();

Now, I want to know if there is a better way to handle this situation as the workaround done does not seems to be a good practice.

Vishal Singh
  • 118
  • 2
  • 6

0 Answers0