如何将它与高阶函数绑定

How to bind this with Higher order functions

我在某个文件中有这个高阶函数

withTry.js

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

我正在尝试在另一个文件中这样调用它;

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*/
 
});

我的问题是如何绑定“someClass”的“this”

你不想绑定它,你想传递动态this值通过:

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

作为 call, you can also use func.apply(this, args) 的替代方法。

接下来您要添加的是 return 语句,用于将 return 值传回 :-)

我的回答和Bergi的基本一样:

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

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

someClass.prototype.func = withTry(function(data){
 console.log(this.s); 
});

var x = new someClass();
x.func();

我意识到,因为你正在调用 x.func,从 withTry 返回的函数已经 this