Javascript 如何清晰地分解两个几乎相似的函数
我有两个非常相似的函数内容,我想通过使代码成为单个函数来清晰地分解代码,但只有几行不同,更准确地说,其中一行代码比其他代码多3行Javascript 如何清晰地分解两个几乎相似的函数,javascript,Javascript,我有两个非常相似的函数内容,我想通过使代码成为单个函数来清晰地分解代码,但只有几行不同,更准确地说,其中一行代码比其他代码多3行 function doStuffForFacebook() { var example = "toto" //about 7 lines of code resizeScale = 1 } functiondoStuffforYoutube() { var example = "toto" //the VERY SAME 7 lines of
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+行分解为一个小的差异似乎是可以改进的
是否有推荐的方法可以做到这一点,也许可以使用类似于回调的方法来实现类似的操作
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最佳实践正确执行此操作?您可以为回调参数提供默认的空函数:
function resizeVideo(callback = function(){}) {
...
callback()
...
}
一个函数中不可能有50行代码。尝试将其拆分为多个较小的函数,然后您将清楚地知道如何执行其余的操作。抱歉,键入错误,这是7行代码。Stll重复完全相同的代码行两次似乎不够干练=>如果可能的话,我想分解请再添加//大约7行代码重构未知代码毫无意义。哦,nil是python在js中的null…呵呵,是ruby Reflection,刚刚改成null OK,我认为回调可能是最合适的方法,但是对于doStuffForFacebook,没有额外的代码,我可以编写resizeVideonull来表示没有其他回调可调用,或者只使用resizeVideo会让javascript理解没有回调?resizeVideo的函数原型定义了一个空函数,如果没有提供,将使用该空函数,如resizeVideo