如果对象方法作为参数传递给函数,如何将对象方法绑定到其上下文

How do I bind an object method to its context if the object method is passed to a function as an argument

提问人:Yevhen Zhemchuzhnykov 提问时间:1/20/2022 更新时间:1/20/2022 访问量:630

问:

我有一个对象,其中包含一个我想传递给特殊函数的方法。这个特殊函数的工作是调用作为参数传递的函数,并将传递给执行/返回/调用的函数的所有参数保存到外部变量中。

const playerPerformance = {
  goals: 18,
  assists: 19,
  total(penalties, tackles) {
    return this.goals + this.assists + penalties + tackles;
  },
};

const calls = [];

function saveCalls(func) {
  return withMemory = (...rest) => {
    calls.push(rest);
    return func(...rest);
    };
  };

const tester = saveCalls(playerPerformance.total);

问题是我不知道如何保存传递函数的上下文。它必须在函数内部完成,而不是这样。我尝试应用里面的方法,但这不能以这种方式工作。saveCallsconst tester = saveCalls(playerPerformance.total.bind(playerPerformance);bind(), call(), apply()saveCalls

当前结果:

tester(2,1) // NaN

...这是可以理解的,因为我失去了上下文,我得到了undefined + undefined + 2 + 1

此代码更改后所需的结果:

tester(2,1) // 40
javascript 应用 调用 绑定

评论


答:

1赞 trincot 1/20/2022 #1

只需创建一个包装函数,就可以为 .该方法就是为此而设计的:thistotalbind

const tester = saveCalls(playerPerformance.total.bind(playerPerformance));