簡體   English   中英

JavaScript:如何組合兩個不同但非常相似的函數?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM