删除循环中的函数创建 - 闭包

时间:2012-11-22 13:19:52

标签: javascript jshint

我想在我的代码中删除函数创建,但我不知道如何?这里的任何人都可以帮助我吗?

    for (var eventName in this.events) {
        var eventFunc = this.events[eventName],
            splitEventName = eventName.split(" "),
            eventType = splitEventName[0],
            eventUI = splitEventName[1];

        Utilities.addEventListener(this.ui[eventUI], eventType, (function(view, eventFunc) {
            return function(e) {
                eventFunc.call(view, e);
            };
        }(this, eventFunc)));
    }

1 个答案:

答案 0 :(得分:3)

您可以将立即调用的函数表达式移出循环并将其转换为正常的函数声明。然后你可以在每次迭代时调用它:

function makeEventListener(view, eventFunc) {
    return function (e) {
        eventFunc.call(view, e);
    };
}
for (var eventName in this.events) {
    var eventFunc = this.events[eventName],
        splitEventName = eventName.split(" "), 
        eventType = splitEventName[0],
        eventUI = splitEventName[1];
    Utilities.addEventListener(this.ui[eventUI], eventType, makeEventListener(this, eventFunc));
}