javascript - JavaScript: 如何组合两个不同但非常相似的函数?

  显示原文与译文双语对照的内容
105 3

在这两个函数

  • 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');
时间:原作者:0个回答

70 1

是否需要将函数合并为一个?试试。

function Test (title, foo, folder = 'FooFolderPath', hostPageUrl = DynamicHost()) {
 return {
 title,
 hostPageUrl,
 url: folder + (foo? foo + '/' : '') + name +'.T.js'
 };
}
//Usage of Functions;
Test('NameParam', 'FooParam')
Test('NameParam', null, 'BarFolderPath', 'BarHostParam')
原作者:
75 1

看起来 foo 参数是distincted参数。使用该命令,但你需要更改参数顺序:

function RunTestCases (name, folder, host,foo) 
 {
 host = host || (foo? 'FooHostParam' : DynamicHost()) ;
 folder = folder || foo? 'FooFolderPath' : 'BarFolderPath')
 const url = (foo? (folder + foo + '/' + name +'.T.js') : (folder + name +'.T.js'));
 return {
 title: name,
 hostPageUrl: host,
 url
 };
}
原作者:
54 0

在两个函数中保持参数顺序相同,然后在参数中添加 foo,然后执行类似 below的操作:

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'));
原作者:
108 3
function RunTest (name, folder, host, foo) {
 host = host || (foo? DynamicHost() : 'FooHostParam');
 folder = folder || 'FooFolderPath';
 returnVal = {
 title: name,
 hostPageUrl: host,
 };
 returnVal.url = foo? folder + name +'.T.js' : folder + foo + '/'+ name +'.T.js';
 return returnVal;
}
原作者:
...