繁体   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