我正在研究 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/