javascript - 如何干净地分解两个几乎相似的函数
问题描述
我有 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 最佳实践的情况下正确执行此操作?
解决方案
你可以为你的回调参数提供一个默认的空函数:
function resizeVideo(callback = function(){}) {
...
callback()
...
}
推荐阅读
- python - 如何使用“请求”导入在 Python 中使用 API 提取数据?
- javascript - 如何在服务器上同时运行 main.js、cros.js 和 server.py
- reactjs - 使用箭头键响应自定义滚动
- flutter - 有没有一种有效的方法可以专注于下一个 textformfield?(扑)
- matlab - Probit:删除完美预测失败的组
- xslt - 如何在 SOA BPEL/XSLT 中遍历子节点并对其进行修改
- ruby-on-rails - 在视图中将带有插值的字符串渲染到 HAML
- python - 在 PyCharm 中调试期间如何查看异常回溯?
- c++ - 仅通过更改数据类型就会出现意外的输出
- reactjs - 是否可以将 Material UI 作为 peerDependency 但将其类型保持为 DevDependency?