Search code examples
javascriptclassthisbindhigher-order-functions

How to bind this with Higher order functions


I have this higher-order function in some file

withTry.js

function withTry(func){
    return function(...args) {
        try{
            
            func(...args);
        }
        catch(error){
            console.log(`ERROR: ${error}`)
        }
    }
}

I am trying to call it in another file like this;

foo.js

const withTry = require('path');

function someClass(){
 this.m = null;
 this.s=0;
}

/*I am using the withTry in class prototypes*/
someClass.prototype.func = withTry(function(data){
 /* 
  The problem is here
  The value of "this" is global which makes sense because it refers to the global of the withTry HOF
*/

 console.log(this.s) /*undefined*/
 
});

My question is how to bind the "this" of the "someClass"


Solution

  • You don't want to bind it, you want to pass the dynamic this value through:

    function withTry(func) {
        return function(...args) {
            try {
                func.call(this, ...args);
    //              ^^^^^^^^^^^
            } catch(error){
                console.log(`ERROR: ${error}`)
            }
        }
    }
    

    As an alternative to call, you can also use func.apply(this, args).

    Next thing you'll want to add is a return statement for passing the return value back out :-)