Functional programming is a programming paradigm
1 The function is the first citizen, it can return a value and can also be used as a parameter of other functions
//console是一个函数 function con(v){ console.log(v) } // execute 也是一个函数 function execute(fn){ fn(1) } //将con函数作为参数传进execute函数 execute(con) // 1
2 Writing method close to natural language
Xiaochi finished eating and then went to take a bath. It can be expressed as eat().bathe()
// 吃饭函数 function eat(eat){ this.e = eat; return this; } // 洗澡函数 function bathe(bathe){ this.b = bathe; return this; } var person = eat("晓池在吃饭").bathe("晓池去洗澡了"); console.log(person.e) // 晓池在吃饭 console.log(person.b) // 晓池去洗澡了
3 Features of Functional Programming
Anonymous functions, that is, functions without names, are very common in functional programming. Sometimes we need to use them (unreused functions) to complete some functions. Let’s learn about it by defining an each function:
// 自定义each函数 function each(arr,func){ var length = arr.length; for(var i = 0 ;i <length; i++){ func(i,arr[i]) } } // 执行each函数,传进一个匿名函数作为该函数的参数 each([1,2,3],function(i,v){ console.log('key:' + i + ',value:' +v); }); //输出内容 //key:0,value:1 //key:1,value:2 //key:2,value:3
Currying: Currying is the technique of transforming a function that accepts multiple parameters into a function that accepts a single parameter (the first parameter of the original function), and returns a new function that accepts the remaining parameters and returns the result.
//定义add函数,并返回一个函数 function add(num){ return function(x){ return num + x; } } add1 = add(1) console.log(add1(3)) // 4
Higher-order function: If there is a function as a parameter or a function returns a function internally, the function can be called a higher-order function. The above each function is considered a type of high-order function.
Conclusion
In actual applications, it is not limited to functional or object-oriented, and is usually a mixture of the two. In fact, many mainstream object-oriented languages are constantly improving themselves, such as adding some features of functional programming languages. Wait, in JavaScript, the two are well combined. The code can not only be very simple and beautiful, but also easier to debug.