30秒学会 JavaScript 片段 · 2022年7月25日

30秒学会 JavaScript 片段 – Call functions with context

Given a key and a set of arguments, call them when given a context.

  • Use a closure to call key with args for the given context.

代码实现

const call = (key, ...args) => context => context[key](...args);

Promise.resolve([1, 2, 3])
  .then(call('map', x => 2 * x))
  .then(console.log); // [ 2, 4, 6 ]
const map = call.bind(null, 'map');
Promise.resolve([1, 2, 3])
  .then(map(x => 2 * x))
  .then(console.log); // [ 2, 4, 6 ]

翻译自:https://www.30secondsofcode.org/js/s/call-functions-with-context