需要绑定或申请部分应用

The need for bind or apply for partial application

本文关键字:请部 应用 绑定      更新时间:2023-09-26

我正在编写函数式javascript研讨会的部分应用程序部分。

我特别需要:

使用部分应用程序创建一个函数,将第一个参数修复为console.log。

示例输出:

var info = logger('INFO:');
info('this is an info message');
// INFO: this is an info message

我天真的解决方案工作,但不使用apply或bind:

function logger(namespace) {
  return (args) => console.log(namespace, args);
};
const info = logger('INFO:');
info('this is an info message');
// INFO: this is an info message

建议的解决方案:

var slice = Array.prototype.slice
function logger(namespace) {
  return function() {
    console.log.apply(console, [namespace].concat(slice.call(arguments)))
  }
}

我错过了什么?为什么需要bind或apply ?

推荐的解决方案将传递所有参数(并且可能在编写时不考虑ES2015)。你的解只会通过第一个参数。我想你是在找(...args) => console.log(namespace, ...args)