javascript - JavaScript:如何组合两个不同但非常相似的函数?
问题描述
在这两个功能内;
url
路径是变化的。- 取决于不同的
url
路径;功能parameters
是变化。
我尝试了几种命名和用法来组合这些功能,但都没有成功!我怎样才能只使用一个功能?提前致谢。
function RunTestCases (name, foo, folder, host) {
host = host || DynamicHost();
folder = folder || 'FooFolderPath';
return {
title: name,
hostPageUrl: host,
url: folder + foo + '/'+ name +'.T.js'
};
}
function RunMonkeyTestCase (name, folder, host) {
host = host || DynamicHost();
folder = folder || 'FooFolderPath';
return {
title: name,
hostPageUrl: host,
url: folder + name +'.T.js'
};
}
//Usage of Functions;
RunTestCases('NameParam', 'FooParam');
RunMonkeyTestCase('NameParam', 'BarFolderPath', 'BarHostParam');
//For some specific usages.
RunTestCases('NameParam', 'FooParam', 'BarFolderPath', 'BarHostParam');
RunMonkeyTestCase('NameParam', null, 'FooHostParam');
解决方案
在两个函数中保持参数顺序相同,然后最后添加foo
参数,然后执行如下操作:
function TestCase(name, folder, host, foo) {
host = host || DynamicHost();
folder = folder || 'FooFolderPath';
let url;
if (foo) {
url = folder + foo + '/' + name + '.T.js';
} else {
url = folder + name + '.T.js'
}
return {
title: name,
hostPageUrl: host,
url: url
};
}
console.log(TestCase('NameParam', 'BarFolderPath', 'BarHostParam', 'FooParam'));
console.log(TestCase('NameParam', 'BarFolderPath', 'BarHostParam'));
console.log(TestCase('NameParam', 'FooParam', 'BarFolderPath', 'BarHostParam'));
console.log(TestCase('NameParam', 'FooHostParam'));
推荐阅读
- unity3d - Android 上的 Unity GPS 位置不经常更新
- python - Python 导入失败并带有崇高的文本,但程序通过控制台运行
- scala - 在另一个生成器中使用 ScalaCheck 生成器
- php - 使用 PHP 检测纯文本中的表情符号
- javascript - 为什么我不能让外部链接成为nofollow?
- python - 如何在 PyQt5 制作的 GUI 窗口中显示来自 picamera 的实时预览?
- javascript - 如何设置标题 zIndex?出现以下错误:无法读取未定义的属性“zIndex”
- javascript - 如何更改 ui 控件上的地图图块类型
- javascript - 刷新时的持久性倒计时
- apostrophe-cms - 无法检索附件 url