【问题标题】:Adding code to an existing function inside loop将代码添加到循环内的现有函数
【发布时间】:2018-03-26 11:03:15
【问题描述】:

在一个对象中,我定义了一些事件:键是事件名称,值是回调函数。这是一个例子:

vm.events = {
    check_node: function(node, selected){
        ...
    },
    uncheck_node: function(node, selected){
        ...
    }
};

我想为这些函数添加一些代码,所以我做了以下操作:

for (var evt in scope.tree.events) {
    if (scope.tree.events.hasOwnProperty(evt)) {
        var cb = scope.tree.events[evt];
        scope.tree.events[evt] = function(...args){
            cb(...args);
            controller.$setDirty();
            scope.$evalAsync();
        };
        scope.tree.view.on(evt.indexOf('.') > 0 ? evt : evt + '.jstree',  scope.tree.events[evt]);
    }

但是 JSHint 会记录以下警告:

Functions declared within loops referencing an outer scoped variable may lead to confusing semantics. (W083)

我该如何解决这个问题?

【问题讨论】:

    标签: javascript jshint


    【解决方案1】:

    您可以使用箭头函数保持在同一范围内:

    for (var evt in scope.tree.events) {
        if (scope.tree.events.hasOwnProperty(evt)) {
            var cb = scope.tree.events[evt];
            scope.tree.events[evt] = (...args) => {
                cb(...args);
                controller.$setDirty();
                scope.$evalAsync();
            };
            scope.tree.view.on(evt.indexOf('.') > 0 ? evt : evt + '.jstree',  scope.tree.events[evt]);
        }
    }
    

    【讨论】:

    • 我仍然收到同样的 JSHint 警告。
    【解决方案2】:

    这就是我解决问题的方法:

    var cb = function(oldCb) {
        return function() {
            var result = oldCb.apply(this, arguments); 
            controller.$setDirty();
            scope.$evalAsync();
            return result;
        };
    };
    
    for (var evt in scope.tree.events) {
        if (scope.tree.events.hasOwnProperty(evt)) {
            var oldCb = scope.tree.events[evt];
            scope.tree.view.on(evt.indexOf('.') > 0 ? evt : evt + '.jstree',  cb(oldCb));
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-06-28
      • 2015-03-28
      • 2011-11-20
      • 2013-08-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多