简体   繁体   English

JavaScript重构通常称为函数

[英]Javascript refactor oftenly called function

I'm working with javascript for quite a long time, but it happens to me often that I come up with the following code: 我使用javascript已有很长时间了,但是我经常想到以下代码:

function1 () {
  // do stuff
  ...
  end_function();
}

function2 () {
  // do stuff
  ...
  end_function();
}

function3 () {
  // do stuff
  ...
  end_function();
}

I know this is in conflict with the DRY principles, but unfortunately, I don't know what to do with it to remove the repetitions. 我知道这与DRY原则相抵触,但是不幸的是,我不知道该如何使用它来消除重复。 Does anyone know the answer? 有人知道答案吗?

There is so many solutions. 有很多解决方案。

One way is wrap function like "am not i am's" answer, 一种方式是自动换行功能,例如“不是我”

another is use higher-order function. 另一个是使用高阶函数。

var end_function = function(callback){

    callback.call();

    // do some stuff 
};

var stuff1 = function(){};
var stuff2 = function(){}:

end_function(stuff1);
end_function(stuff2);

It would be in conflict with DRY if you code the end_function directly into the other functions. 如果将end_function直接编码到其他函数中,将与DRY冲突。 Ultimately you do need some syntax to invoke the code that you abstracted into its own function. 最终,您确实需要某种语法来调用您抽象成其自身功能的代码。

If functions are grouped together into an Object, I suppose you could enumerate the properties of the object, and wrap each function, but that's probably only worth it you have many of these functions. 如果将功能分组到一个对象中,我想您可以枚举对象的属性并包装每个功能,但是拥有许多这些功能可能仅是值得的。

var funcs = {
    function1 () {
      // do stuff
    },
    function2 () {
      // do stuff
    },
    function3 () {
      // do stuff
    }
};

Object.keys(funcs).forEach(function(key) {
    var orig = funcs[key];
    funcs[key] = function() {
        orig.apply(this, arguments);
        end_function();
    };
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM