簡體   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