javascript - 需要bind或apply申请部分申请

标签 javascript ecmascript-6

我正在研究 functional javascript workshop 的部分应用部分.

具体来说,我需要:

Use partial application to create a function that fixes the first argument to 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)或应用?

最佳答案

推荐的解决方案将传递所有参数(并且可能是在不考虑 ES2015 的情况下编写的)。您的解决方案将仅通过第一个参数。我认为您正在寻找 (...args) => console.log(namespace, ...args)

关于javascript - 需要bind或apply申请部分申请,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32728625/

相关文章:

javascript - 将十进制值转换为 32 位浮点十六进制

javascript - 'infinite' 模式下的 Backbone.Paginator 在 model.destroy 上抛出 'Maximum call stack size exceeded'

javascript - 使用 babel by gulp-watch 转换为 ES5 不起作用

javascript - 使用子组件的 $emit 将数据发送到父组件不适用于 Vue

javascript - Vue JS 如何根据数组值删除对象

javascript - 带有自定义颜色管道的 AG-Grid

javascript - 如何将视频通话添加到 nativescript 应用程序

javascript - 按顺序执行Promise : understanding a claim made about this example code

javascript - 将键值对传递给 JavaScript 文件

javascript - 从其他函数创建一个函数,但使用预填充参数