JavaScript系列:函數式編程(開篇)

來源:互聯網
上載者:User

標籤:概念   expected   簡單   throw   class類   等等   ted   語言   實現   

前言:

上一篇介紹了 函數回調,高階函數以及函數柯裡化等進階函數應用,同時,因為正在學習JavaScript·函數式編程,想整理一下函數式編程中,對於我們日常比較有用的部分。

 

為什麼函數式編程很重要?

      學習過C++,java這些物件導向程式設計語言,我們大概都知道物件導向編程就是把目標問題分成幾個部分,實現各部分的功能,再組合成一個更強大的對象。雖說JavaScript不是物件導向程式設計語言(雖然ES6已經出現了Class類這種對象,在此暫且不說),但它卻是一種完完全全支援函數式編程的語言,利用函數式編程,我們也可以將問題分解成幾個部分(函數)來解決。函數式編程也通過組合其他函數構造更加強大的函數,以實現更抽象的行為。 
  1. 以函數為抽象單元
    • 比如,我們想自訂列印錯誤,我們可以將錯誤,警告等等概念抽象為一個函數
      1 function fail(err){2 throw new Error(err);3 }4 function warn(err){5 console.log("Warning thing:%s",err);6 }   

       

  2. 封裝和隱藏
    • Javascript中沒有提供直接隱藏資料的方式(也就是沒有私人變數),但是可以使用閉包來實現隱藏資料(實現私人變數的定義)
       1 var Person=function(){ 2 // 定義私人變數 3 var school="SCUT"; 4 // 定義公用介面方法 5 return { 6 name:‘‘, 7 setName:function(name){ 8 this.name=name; 9 },10 getName:function(){11 return this.name;12 },13 getSchool:function(){14 return school;15 }16 }17 }18 var person1=new Person()19 // => undefined20 person1.school21 // => undefined22 person1.getSchool()23 // => "SCUT"

       

       1 var Person=function(){ 2 this.name=‘‘; 3   this.school="SCUT"; 4 this.setName=function(name){ 5 this.name=name; 6 }; 7 this.getName=function(){ 8 return this.name; 9 };10 this.getSchool=function(){11 return this.school;12 }13 }14 var person1=new Person()15 person1.getSchool()16 //=> "SCUT"17 person1.school18 //=> "SCUT"19 person1.school=‘JYYz‘20 person1.getSchool()21 //=> "JYYz"

       

      由第一個例子我們可以看到 school 相當於私人變數,無法通過執行個體訪問
      1 person1.school2 // => undefined

       

      而第二個例子可以訪問,並且可以進行修改。
  3. 以函數為行為單位
    • 提供一種簡單的儲存和傳遞行為的離散單元
    • 舉一個簡單的例子:數組索引行為,稱之為nth,簡單如下
       1 nativeNth(‘hello‘,2) 2 //=> "l" 3 nativeNth({},2) 4 //=> undefined 5 可以看到,當傳入不正確的值時候,會發生錯誤;對之進行修改如下: 6 function nativeNth(a,index){ 7 if(!Number.isInteger(index)) fail("Expected a number as the index"); 8 if(!Array.isArray(a) && typeof a !==‘string‘) 9 fail("Non supported on non-indexed type");10 if((index<0)||(index>a.length-1))11 fail("index value is out of bounds");12 return a[index];13 }

       這樣子我們構建了nth函數的抽象方式 總結:概括的說,函數式編程包括以下幾點:確定抽象,並為其構建函數利用已有的函數來構建更為複雜的抽象通過已有的函數傳給其他的函數來構建更加複雜的抽象 通過函數,我們可以把各部分功能封裝在各個抽象裡面,提供一個介面,實現邏輯的獨立性。

JavaScript系列:函數式編程(開篇)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.