JavaScript:如何结合两个不同但非常相似的功能?

时间:2018-08-30 12:44:46

标签: javascript function parameters arguments

在这两个函数中;

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

4 个答案:

答案 0 :(得分:1)

您需要将功能合并为一个吗?试试吧。

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

答案 1 :(得分:1)

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

答案 2 :(得分:1)

看起来foo参数是唯一的参数。我会用它,但是您需要更改参数顺序:

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
  };
}

答案 3 :(得分:0)

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;
}