Jac*_*cco 5 javascript binding anonymous-function
我经常要绑定?一些需要参数的函数.我使用的解决方案是将函数包装在匿名函数内部.
function foo( arg_0 ) {
// do stuff with: arg_0
}
function bar() {
var abc;
// stuff happens
abc = 'some value';
attachEventHandler(elementId, 'click', function(){foo( abc );});
}
bar();
Run Code Online (Sandbox Code Playgroud)
有更优雅的方式吗?
SLa*_*aks 10
你可以做一个曲棍球,像这样:
function curry(func) {
var functionArgs = Array.prototype.slice.call(arguments, 1);
return function() { return func.apply(this, functionArgs); };
}
Run Code Online (Sandbox Code Playgroud)
用法:
attachEventHandler(elementId, 'click', curry(foo, abc) );
Run Code Online (Sandbox Code Playgroud)
或者:
Function.prototype.curry = function() {
var func = this, functionArgs = arguments;
return function() { return func.apply(this, functionArgs); };
}
Run Code Online (Sandbox Code Playgroud)
用法:
attachEventHandler(elementId, 'click', foo.curry(abc) );
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
378 次 |
| 最近记录: |