Javascript 委托-构造/执行-时间参数

Javascript 委托-构造/执行-时间参数,javascript,delegates,Javascript,Delegates,我有一个helper函数,它允许我在不同的上下文中调用函数。这很简单: function delegate(that, thatMethod) { return function() { return thatMethod.apply(that,arguments); } } 如果我不想在函数执行时计算变量,这是可以的,但有时我想给出在构造时固定的委托函数值。 样本: 所以我是施工时间和其他一切执行时间 这样做的缺点是它看起来很难看。有更好的方法吗?我能把它隐藏在函数中吗? 谢谢您可以

我有一个helper函数,它允许我在不同的上下文中调用函数。这很简单:

function delegate(that, thatMethod)
{
    return function() { return thatMethod.apply(that,arguments); }
}
如果我不想在函数执行时计算变量,这是可以的,但有时我想给出在构造时固定的委托函数值。
样本:

所以我是施工时间和其他一切执行时间
这样做的缺点是它看起来很难看。有更好的方法吗?我能把它隐藏在函数中吗?


谢谢

您可以使用绑定功能:

var callbacks = new Array();
for(var i = 0; i < 5; i++)
{
    //callbacks.push(delegate(window, function() { alert(i) }));
    callbacks.push(function(n) { alert(n) }.bind(window, i);
}
callbacks[3]();
var callbacks=newarray();
对于(变量i=0;i<5;i++)
{
//push(委托(窗口,函数(){alert(i)}));
callbacks.push(函数(n){alert(n)}.bind(窗口,i);
}
回调[3]();
但是bind并没有在IE上实现(不知道IE9),关于如何让它在IE上工作,请参见

function delegatedd( that, thatMethod )
{
    if(arguments.length > 2)
    {
        var _params = [];
        for(var n = 2; n < arguments.length; ++n) 
            _params.push(arguments[n]);
        return function() { return thatMethod.apply(that,_params); }
    }
    else
        return function() { return thatMethod.call(that); }
}
function(foo) {
    return delegate(window, function() {
        alert(foo);
    });
}(i)
var callbacks = new Array();
for(var i = 0; i < 5; i++)
{
    //callbacks.push(delegate(window, function() { alert(i) }));
    callbacks.push(function(n) { alert(n) }.bind(window, i);
}
callbacks[3]();