zam*_*uts 8 javascript node.js
在Javascript(Node.js上下文)中,我Function.prototype.bind经常使用:bind允许更改调用上下文并可选地提供其他前置参数.
是否有任何关于附加论点的建议?有几次我遇到了在Node.js中追加而不是prepend的需要,所以我可以坚持它的函数签名模式.
现在是一个半实用和简化的例子; 我正在使用异步模块的eachSeries方法.
首先,一个包装回调的实现(工作,但很长的路):
function func(something,callback) {
async.eachSeries(
[1,2,3],
function iterator(item,asyncCallback) {
// do stuff
asyncCallback(err||null);
},
function finished(err) {
// `callback` expects 2 arguments
// `err` should always be the first arg, null or otherwise
// `something` (unrelated to the async series) should be maintained
callback(err,something);
}
);
};
Run Code Online (Sandbox Code Playgroud)
而现在有点短:
function func(something,callback) {
async.eachSeries(
[1,2,3],
function iterator(item,asyncCallback) {
// do stuff
asyncCallback(err||null);
},
callback.bindAppend(this,something)
// pseudo-equiv: `callback.bind(this,err,something);`
);
};
Run Code Online (Sandbox Code Playgroud)
在第二个例子中,它err是从回调中携带eachSeries的asyncCallback,something而是由其他方式提供的.为了澄清,我正在寻找替换bindAppend"更短"的例子,它将具有function finished"更长"例子中的功能等价物.
也许我的设计存在缺陷,需要重新设计,或者这只是过早优化的另一种情况.但是,我寻求的功能可以提供以下好处:
一个答案是从分叉的Function.prototype.bind polyfill中推出自己的.但是,我正在寻找一个我没有看到的本机实现,一个接近本机的解决方案,或者已经完成了艰苦工作的实用程序模块(优化,测试等). 仅供参考,除前者之外的任何其他解决方案实际上都会使功能优势#2恶化.
mpm*_*mpm 11
假设我理解了这个问题,我第一次尝试用它进行测试:
Function.prototype.bindAppend = function(context) {
var func = this;
var args = [].slice.call(arguments).slice(1);
return function() {
return func.apply(context, [].slice.call(arguments).concat(args));
}
}
Run Code Online (Sandbox Code Playgroud)
测试:
Function.prototype.bindAppend = function(context) {
var func = this;
var args = [].slice.call(arguments).slice(1);
return function() {
return func.apply(context, [].slice.call(arguments).concat(args));
}
}
describe('bindAppend', function() {
beforeEach(function() {
this.obj = {
value: "a",
func: function() {
return this.value + [].slice.call(arguments).join('');
}
}
});
it('should work properly', function() {
expect(this.obj.func.bindAppend(this.obj, "c")("b")).toEqual("abc");
});
it('should work properly', function() {
expect(this.obj.func.bindAppend(this.obj, "c", "d")("b")).toEqual("abcd");
});
it('should work properly', function() {
expect(this.obj.func.bindAppend(this.obj, "d")("b", "c")).toEqual("abcd");
});
})
Run Code Online (Sandbox Code Playgroud)
工作版:https://mparaiso.github.io/playground/#/gist/hivsHLuAuV