首页 > 解决方案 > 如何干净地分解两个几乎相似的函数

问题描述

我有 2 个非常相似的函数内容,我想通过使其成为一个函数来干净地分解代码,但只有几行不同,更准确地说,其中一个比其他的多 3 行代码。

function doStuffForFacebook() { 
  var example = "toto"
  //about 7 lines of code

  resizeScale = 1
}

functiondoStuffforYoutube() {
  var example = "toto"
  //the VERY SAME 7 lines of code as those inside doStuffForFacebook()

  //the 3 lines which are different from above
  if ( typeof cryptoVideoX !== "undefined" && cryptoVideoX !== null && cryptoVideoX !== 0 ) {
     var vidRatio = cryptoVideoX / netVideoY;
  } else { //no crypto video add-on by source
      var vidRatio = netVideoRatio;
  }
  var manually_recalculated_width_to_have_full_screen_height_video = Math.round(vidRatio * winHeight);// fb only accepts rounded values
            $fbPlayer.attr('data-width', manually_recalculated_width_to_have_full_screen_height_video );

  resizeScale = 1
}

我真的很想将所有这些长的 7 行以上的行重复为 1 小行的差异似乎是可以改进的。

有没有推荐的方法来做到这一点,也许使用类似于回调的东西可以做类似的事情?

function doStuffForFacebook() { 
  resizeVideo(null);//nil because here no callback is necessary
}

functiondoStuffforYoutube() {
  resizeVideo(addSomeCodeCallback);
}
function resizeVideo(callback) {
  var example = "toto"
  //the 7 lines of common CODE
  callback();          
  resizeScale = 1
}
function addSomeCodeCallback() {
  if ( typeof cryptoVideoX !== "undefined" && cryptoVideoX !== null && cryptoVideoX !== 0 ) {
     var vidRatio = cryptoVideoX / netVideoY;
  } else { //no crypto video add-on by source
      var vidRatio = netVideoRatio;
  }
  var manually_recalculated_width_to_have_full_screen_height_video = Math.round(vidRatio * winHeight);// fb only accepts rounded values
            $fbPlayer.attr('data-width', 
  manually_recalculated_width_to_have_full_screen_height_video );
}

我知道我可以,但我不想:为之前的内容创建函数,为之后的内容创建另一个函数,因为它们都更符合逻辑而不是拆分,因为它们属于大型 if/else 块。

如何在尊重 javascript 最佳实践的情况下正确执行此操作?

标签: javascript

解决方案


你可以为你的回调参数提供一个默认的空函数:

function resizeVideo(callback = function(){}) {
  ...
  callback() 
  ...
}

推荐阅读