繁体   English   中英

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

[英]JavaScript: Using dedicated functions or general purpose functions with arguments?

我想知道哪种方法更适合在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")
  }
}

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM