【发布时间】: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