簡體   English   中英

函數式編程實踐

[英]Praxis in Functional Programming

我正在學習函數式編程,並且遇到了編寫函數的這種方式:

function createCounter (){
  let counter = 0
  return {
    increment: function() {
      counter += 1
    },
    currentValue: function() {
      return counter
    }
  }
}

這是用JavaScript編寫函數的常用方法嗎? 我已經進行了至少3年的編程,而且我任何時候都無法回憶起。 它看起來像是對象和功能的混合體。 是的,我知道函數是JS中的對象。 但是我只想知道這是否很常見,應該在工作中開始使用。

讓我們看看如何使用它:

 function createCounter (){ let counter = 0; return { increment: function() { counter += 1 }, currentValue: function() { return counter } }; } let counter0 = createCounter(); console.log(counter0.currentValue()); //0 counter0.increment(); counter0.increment(); console.log(counter0.currentValue()); //2 

可以看到, counter0對象公開了兩個函數,可用於讀取或遞增計數器。

是的,這是一種普遍的方式,在現代代碼中則很少。

但是,如果您可以使用ES6 / Ecmascript 2015( 請參閱兼容性表 ),則不建議這樣做。 從那時起, 就引入了JavaScript,並且由於與其他編程語言的相似性,我想說使用它們為您提供了更易於理解的代碼。

例:

class Counter {
  constructor(initialValue = 0) {
    // using underscore is common practice to state that it shouldn't be publically accessed
    this._currentValue = initialValue;
  }

  increment() {
    this._currentValue++;
  }

  get currentValue() {
    return this._currentValue;
  }
}

用法:

let counter = new Counter();
counter.increment();
console.log(counter.currentValue); // 1

另外,您可以避免使用吸氣劑,而只需像其他任何(公共)變量一樣訪問currentValue即可。 根據需要編輯代碼,以遵循功能編程的慣例。


還值得學習:

如今,這兩個功能都無法在Firefox中使用,因此除非您通過Babel編譯代碼,否則我仍會繼續使用它們。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM