Reading Notes on the essence of JavaScript programming-Chapter 5: Functional Programming

Source: Internet
Author: User

5.1 Abstraction: in the final analysis, the program is to solve the problems in life, but most of the time the problems in reality are always very complicated. The solution to minimize the complexity of the program is to abstract it. Abstract many complex relationships into simpler logics and apply them to programs. This is my abstract understanding of programming. Function programming creates abstraction through clever function combinations.

5.2 high-order functions: Simply put, high-order functions are functions that process other functions, that is, function nesting. Javascript is a function-oriented language. In the Javascript world, everything is a value type, and of course functions are no exception. The most obvious difference between it and other languages (such as C #) Is that functions can be generated and passed exactly like values. You can use a function as a parameter of another function, or define a new function within a function. Of course, you may think of lambda expressions in C #, which can also accomplish some similar functions, but JS is a pure Dynamic Language, and processing functions are its housekeeping skills. Lambda in C, the use of VaR only increases the dynamic nature to a certain extent, and its flexibility is far inferior to that of Js. The above is my personal understanding. I didn't talk about this in the book. Most of the books show function programming in the form of instances. Let's try the code below (of course, the code must be the same as in the book, and some of them are highly imitation ).

A simple functional programming example

View code

function calculate(calMethod,numA,numB){    return calMethod(numA,numB);}function add(num1,num2){    return num1+num2;}function multiply(num1,num2){    return num1*num2;}var result1 = calculate(add,1,2);var result2 = calculate(multiply,1,2);alert("result1:"+result1+",result2:"+result2);

In the above example, the function is a clear feature of values. Another common type of high-order function is to modify the value of the input function, as shown below:

View code

function initMethod(method1){    return function(num1)    {        return method1(num1);    }}function changedMethod(num1){    return num1*num1;}var testMethod = initMethod(changedMethod);var result = testMethod(2);alert(result);

The above example reminds me of the recent dependency injection in Asp.net MVC, which transfers an object with specific functions to the current class through the constructor in C, the functions of the current class are actually implemented by passing objects. The proxy mode should also be like this.

Our common sum () function is actually a variant of an algorithm, and this function is a condensed function. Below is an example of the condensed function:

View code

// Function reduce (combine, base, array) {foreach (array, function (element) {base = combine (base, element) ;}); return base ;} function add (a, B) {return a + B;} function foreach (array, Action) {for (VAR I = 0; I <array. length; I ++) {Action (array [I]) ;}} function Sum (numbers) {return reduce (ADD, 0, numbers );} alert (sum ([1, 2, 3]);

The reduce function repeatedly calls a function to add all values in an array to a base data base. In this way, all the values in the logarithm group are calculated according to certain rules. Here we add and change the combine parameter to implement the specific operation you want. In addition, it should be noted that the function is placed in the first place when it is passed as a parameter. This is a Convention. For the specific reason, the declaration in the book will be discussed later.

So far, I have summarized the reading of functions in the function:

1. Use external functions (minimum ).

2. functions that can be read as parameters.

3. Define and call the function within the current function.

4. can read the function itself (recursion ).

Let's look at another function to accept an array and return the number of 0 in the array.

View code

Function reduce (combine, base, array) {foreach (array, function (element) {base = combine (base, element) ;}); return base ;} function foreach (array, action) {for (VAR I = 0; I <array. length; I ++) {Action (array [I]) ;}} function countzeros (array) {function counter (total, element) {return total + (0 === element? 1: 0); // The line commented out below is an alternative // return total + (0 = element);} return reduce (counter, 0, array);} alert (countzeros ([,]);/* handsome !, Convert true to an integer. True indicates 1, false indicates 0.var A = 1 + true; alert (a); * // * var A = 1 + false; alert (); */

In the preceding example, return total + (0 = element? 1: 0) It is very clever, but I tried a new implementation method return total + (0 = element ), after experiment, I found that when bool and number are added, true will change to 1, and false will change to 0. In this way, in many cases, we can judge that the addition and subtraction operations are done in one go, which is quite good.

Next is a ing array, which is a basic algorithm related to the array. Like the preceding conventional function, each value in the array can be processed, but the return value of the function is not discarded, but a new function is constructed.

View code

Function foreach (array, Action) {for (VAR I = 0; I <array. length; I ++) {Action (array [I]) ;}// map the Array Function Map (func, array) {var result = []; foreach (array, function (element) {result. push (func (element) ;}); return result ;}alert (MAP (math. round, [1.1, 3.3, 2.2]);

5.4 other function skills: when using higher-order functions, JS operators are not functions. Just like in the previous example, we need to define an add function, but every time we write and call this code, it is obviously annoying. We can do this:

View code

VaR op = {"+": function (a, B) {return a + B ;}, "=": function (a, B) {return a = B ;}, "=": function (a, B) {return a === B ;},"! ": Function (a) {return! A;}/* and so on. You can add common operations as needed */} // the following method to complete the sum reduce (OP ["+"], 0, 3, 4, 5, 6]);

Note: Common JavaScript Functions

1. Call ()

View code

// Call () function usage 1 function class1 () {This. name = "class1"; this. shownam = function () {alert (this. name) ;}} function class2 () {This. name = "class2";} var C1 = new class1 (); var C2 = new class2 (); // call function enables the method in C1 to execute c1.shownam on the C2 object. call (C2); // result: class2 // call () function usage 2 function class1 () {This. showtxt = function (txt) {alert (txt) ;}} function class2 () {// call class1.call in class2, which overwrites the objects in class1. To complete the inheritance. Class1.call (this);} var C2 = new class2 (); c2.showtxt ("cc ");

2. There is also an apply () method corresponding to call. For the difference between the two, see: http://www.cnblogs.com/fighting_cp/archive/2010/09/20/1831844.html

Note: although the content in this chapter is small, it involves a lot of algorithms, and some of them are not well understood. What I don't understand, I can't really write it out. I will start watching it every day and add it slowly.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.