0

我想在我的代码中删除函数创建,但我不知道怎么做?这里有人可以帮助我吗?

    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)));
    }
4

1 回答 1

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));
}
于 2012-11-22T13:24:19.763 回答