JavaScript:使用专用函数还是带有参数的通用函数?

时间:2018-07-21 20:40:17

标签: javascript function class ecmascript-6

我想知道哪种方法更适合在JavaScript类中创建函数:

  1. 具有每个专用于一个特定操作的功能列表。
  2. 具有一个通用函数,该函数接受参数来决定执行什么。

我相信第一个选项提供了一个不错的界面,但可能会导致多余的代码,第二个选项是干净,灵活的,但可能会导致混淆。


我真的不知道如何问这个问题,所以我想通过一个代码示例来解释它。

假设我们有这些用于打印生物名称的类。

class GeneralPurposePrint {
  constructor (args) {
    this.isHuman = args.isHuman || false;
    this.isOld = args.isOld || false;
    this.name = args.name || "Nameless" 
  }

  //This is what I mean by "general purpose function"
  //arguments may as well come with the printName functions...
  printName(){
    const type = this.isHuman ? "the human" : "the animal";
    const age = this.isOld ? "Old" : "Young";

    console.log(`${age} ${this.name} ${type}`)
  }
}


class DedicatedPrint {
  constructor (name) {
    this.name = name;
  }

  //And by dedicated functions I mean the following functions here
  printOldHuman() {
    console.log("Old human", this.name, "the human")
  }

  printYoungHuman() {
    console.log("Young", this.name, "the human")
  }

  printOldAnimal() {
    console.log("Old", this.name, "the animal")
  }

  printYoungAnimal() {
    console.log("Young", this.name, "the animal")
  }
}

这个问题纯粹出于好奇,也许最好同时使用这两种方法。而且,请不要介意我编写的时髦代码示例,您可能会想到类的相似结构,用于选择排序算法,连接类型,创建形状等。

1 个答案:

答案 0 :(得分:0)

那是一个设计决定,所以您应该问自己GeneralPurposePrint是否真的老了,还是有时候是人类的,有时不是?如果不是,那绝对不是类的属性。为了减少第二种方法的冗余代码,您可以将参数传递给该方法:

printName(old, human) {
  console.log((old ? "Old" : "Young") + this.name + (human ? "the human" : "the animal"));
}
相关问题