[英]JavaScript: How to combine two different but pretty similar functions?
在這兩個職能范圍內;
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');
你需要將功能組合成一個嗎? 試試吧。
function Test (title, foo, folder = 'FooFolderPath', hostPageUrl = DynamicHost()) {
return {
title,
hostPageUrl,
url: folder + (foo ? foo + '/' : '') + title + '.T.js'
};
}
//Usage of Functions;
Test('NameParam', 'FooParam')
Test('NameParam', null, 'BarFolderPath', 'BarHostParam')
在兩個函數中保持參數順序相同,然后在參數中添加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'));
看起來foo
參數是區別的...我會使用它,但你需要更改params順序:
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
};
}
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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.