Talking about javascript functional programming and javascript Functions
Function programming is a type of programming paradigm.
1 function is the first citizenCan return values or be used as parameters of other functions.
// Console is a function con (v) {console. log (v)} // execute is also a function execute (fn) {fn (1)} // pass the con function as a parameter to the execute function execute (con) // 1
2. Writing Method close to natural language
Xiao Chi eats the meal and then takes a bath, which can be shown as eat (). bathe ()
// Function eat (eat) {this. e = eat; return this;} // function of the bath function bathe (bathe) {this. B = bathe; return this;} var person = eat ("Xiao chi is eating "). bathe ("Xiao Chi has taken a bath"); console. log (person. e) // Xiao chi is in the dining console. log (person. b) // Xiao Chi has taken a bath.
3 features of functional programming
Anonymous functions, that is, functions without names, are common in functional programming. Sometimes we need to use them (non-reusable functions) to complete some functions, the following describes how to define an each function:
// Function each (arr, func) {var length = arr. length; for (var I = 0; I <length; I ++) {func (I, arr [I])} // execute the each function, upload an anonymous function as the function parameter each ([1, 2, 3], function (I, v) {console. log ('key: '+ I +', value: '+ v) ;}); // output content // key: 0, value: 1 // key: 1, value: 2 // key: 2, value: 3
Kerihua: kerihua converts a function that accepts multiple parameters into a function that accepts a single parameter (the first parameter of the original function, and return the technology of the new function that accepts the remaining parameters and returns the result.
// Define the add function and return a function add (num) {return function (x) {return num + x ;}} add1 = add (1) console. log (add1 (3) // 4
High-order functions: a function is a high-order function that is returned as a parameter or function. The above each function is a type of high-order function.
Conclusion
In actual applications, it is not limited to functional or object-oriented methods. Usually, they are used in combination. In fact, many mainstream object-oriented languages are constantly improving themselves, for example, some features of functional programming languages are added. In JavaScript, the two are well combined. The code can be very simple, elegant, and easier to debug.