首页 > 解决方案 > JavaScript:如何组合两个不同但非常相似的函数?

问题描述

在这两个功能内;

我尝试了几种命名和用法来组合这些功能,但都没有成功!我怎样才能只使用一个功能?提前致谢。

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');

标签: javascriptfunctionparametersarguments

解决方案


在两个函数中保持参数顺序相同,然后最后添加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'));


推荐阅读