【问题标题】:Perform initial task with parameters before executing function in JS在 JS 中执行函数之前使用参数执行初始任务
【发布时间】:2019-11-13 18:03:57
【问题描述】:

我正在制作一个工具。该工具应该能够接受参数,对参数执行初始任务,然后根据调用的函数返回结果。

我的第一次尝试是使用一个对象。但我不得不在每个函数上重复最初的任务

const test1 = {
  add: (a, b) => {
    a = a + 1; // This part became repetitive
    b = b + 1; // and I had to copy it to other function
    return a + b;
  },
  multiply: (a, b) => {
    a = a + 1;
    b = b + 1;
    return a * b;
  }
}
console.log("test1=" + test1.add(1, 2));

然后我尝试使用一个函数并改用 switch case。这就是我目前用于解决此问题的方法。这是最好的解决方案吗?

function test2(o, a, b) {
  a = a + 1;
  b = b + 1;
  switch (o) {
    case "add":
      return (a + b);
    case "multiply":
      return (a * b);
  }
}
console.log("test2=" + test2("add", 1, 2));

但后来我想到了使用类。我通过创建新的类对象来调用它并调用类的函数

class test3 {
  constructor(a, b) {
    this.a = a + 1;
    this.b = b + 1;
  }
  add() {
    return this.a + this.b;
  }
  multiply() {
    return this.a * this.b;
  }
}
console.log("test3=" + new test3(1, 2).add());

这似乎比 switch case 更简洁、更易于阅读,但我担心我会一遍又一遍地为一个我会使用一次但随后丢弃的函数创建一个新类。

有没有办法让类使用参数执行初始任务,但保持函数静态,这样我就不必在每次需要使用时实例化 new 类对象?

我觉得我错过了什么。有没有更好的方法来解决这个问题?

【问题讨论】:

  • 为什么不直接将参数传递给类中的函数呢?那么你可以这样称呼它:test3.add(1,2)。我认为它更具可读性,而且你已经摆脱了new

标签: javascript function class object ecmascript-6


【解决方案1】:

我会像这样使用模块模式:

function test1(a, b) {
  const _a = a + 1;
  const _b = b + 1;  
  function addNums() {    
    return _a + _b;
  }
  function multiplyNums() {    
    return _a * _b;
  }
  return {
    add: addNums,
    multiply: multiplyNums
  }  
}

const api = test1(1,2);
console.log(api.add());
console.log(api.multiply());

【讨论】:

    【解决方案2】:

    你做数学的时候不能加吗?

     
    
    const test1 = {
      add: (a, b) => ++a + ++b,
      multiply: (a, b) => ++a * ++b
    }
    console.log(test1.add(1, 2));
    console.log(test1.multiply(1, 2));

    【讨论】:

      猜你喜欢
      • 2013-11-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-10
      • 2015-02-02
      • 2019-05-13
      相关资源
      最近更新 更多