如何将其与高阶函数绑定

问题描述

我在某些文件中具有此高阶功能

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的替代方法,您也可以使用func.apply(this,args)

接下来要添加的是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