Use functional programming techniques to write beautiful JavaScript_javascript skills

Source: Internet
Author: User
Write a beautiful JavaScript level using functional programming technology: elementary

Shantanu Bhattacharya (shantanu@justawordaway.com), Chief Consultant, Siemens Information Systems Limited

July 20, 2006

Functional or Declarative Programming is a very powerful programming method and is gradually becoming popular in the software industry. This article introduces some related functional programming concepts and provides examples to effectively use these concepts. The author will explain how to use JavaScript (TM) (JavaScript can import the construction and features of functional programming) to write beautiful code.

Introduction

Functional programming languages have been in the academic field for a long time, but historically they have no rich tools and libraries available for use. With the emergence of Haskell on the. NET platform, functional programming has become more popular. Some traditional programming languages, such as C ++ and JavaScript, introduce some structures and features provided by functional programming. In many cases, repeated JavaScript code leads to poor coding. If you use functional programming, you can avoid these problems. In addition, you can use the functional programming style to write more elegant callbacks.

Function-based programming only describes the operations performed on program input, without the need to use temporary variables to save intermediate results. The key is to capture "what and why", rather than "how to do ". Compared with procedural programming that focuses on executing continuous commands, functional programming focuses on the definition of functions rather than the implementation of state machines. Large-scale knowledge management system applications have benefited a lot from the functional programming style, because functional programming simplifies development.

Because functional programming uses a completely different way of organizing programs, programmers who are used to using imperative examples may find functional programming a little hard to learn. In this article, you will learn some examples about how to use the functional style and use JavaScript to write good and elegant code. I will discuss:

  • Function programming concepts include anonymous functions, different methods for calling functions, and methods for passing functions as parameters to other functions.


  • The Application of functional concepts includes extended array sorting, beautiful code generated by Dynamic HTML, and applications of series functions.



Functional Programming Concepts

Please tell everyone. Please submit this to: Digg Slashdot

Many developers know how to encode the language that specifies a solution by describing "how to do. For example, to compile a function to calculate factorial, I can write a loop to describe the program, or use recursion to find the product of all numbers. In both cases, the computing process is described in detail in the program. Listing 1 shows a possible C code used to calculate a factorial.


List 1. Process-style factorial

int factorial (int n){ if (n <= 0)  return 1; else  return n * factorial (n-1);}


This type of language is also calledProceduralProgramming languages, because they define the process of solving the problem. Functional programming is significantly different from this principle. In functional programming, You need to describe the question "What is it ". A functional programming language is also calledDeclarativeLanguage. The same factorial program can be written as allNThe product of numbers. The typical function program for calculating factorial looks like the example in Listing 2.


List 2. factorial in a functional Style

factorial n, where n <= 0 := 1factorial n  := foldr * 1 take n [1..]


The second statement indicates that you want to get the first value from 1.NNumber list (take n [1..]), And then find out their product. 1 is the base element. This definition is different from the previous example. There is no loop or recursion. It is like the arithmetic definition of a factorial function. Once you understand the library function (takeAndfoldr) And mark (list notation [ ]), It is easy to write the code, and the readability is also good.

You can write routines with only three lines of Miranda code. Based on the parameters, You can traverse each node of the n-tree with breadth-first or depth-first, and the elements can be of any common type.

Historically, functional programming languages are not popular for many reasons. But recently, some functional programming languages are entering the computer industry. One example is Haskell on the. NET platform. In other cases, some existing languages borrow some concepts from functional programming languages. Some C ++ implementation iterators and continuation, as well as some functional construct provided in JavaScript, are examples of such borrow. However, the general language programming examples have not changed by using function-based construction. JavaScript has not become a functional programming language because of the addition of functional structures.

I want to talk about the beauty of functional structures in JavaScript and how to use them in daily coding and work. We will start with some basic functions and use them to view more interesting applications.

Anonymous Functions

In JavaScript, you can write anonymous functions or functions without names. Why do we need such a function? Continue reading, but first we will learn how to write such a function. If you have the following JavaScript Functions:
Listing 3. Typical Functions

function sum(x,y,z) { return (x+y+z);}


Then the corresponding anonymous function should look as follows:
Listing 4. Anonymous Functions

function(x,y,z) { return (x+y+z);}


To use it, you need to write the following code:


Listing 5. Applying anonymous Functions

var sum = function(x,y,z) { return (x+y+z);}(1,2,3);alert(sum);


Use functions as values

You can also use a function as a value. You can also assign values to variables of functions. In the last example, you can also perform the following operations:
Listing 6. assigning values using functions

var sum = function(x,y,z) { return (x+y+z);}alert(sum(1,2,3));


In the example in Listing 6, the value assigned to the variable sum is the function definition itself. In this way, sum becomes a function that can be called anywhere.

Different Methods for calling Functions

JavaScript allows you to call a function in two ways, as shown in listing 7 and 8.


Listing 7. Typical function applications

alert (“Hello, World!");


Or


Listing 8. Using functions as expressions

(alert) (“Hello, World!");


You can also write the following code:


Listing 9. You can use the function immediately after defining it.

( function(x,y,z) { return (x+y+z) } ) (1, 2, 3);


You can write a function expression in parentheses and then pass it to the parameter for calculation. Although the function name in the example in listing 8 is directly included in the brackets, this is not the case when you use it as shown in listing 9.

Passing functions as parameters to other functions

You can also pass functions as parameters to other functions. Although this is not a new concept, it is widely used in subsequent examples. Function parameters can be passed, as shown in listing 10.


Listing 10. Passing the function as a parameter and applying the Function

var passFunAndApply = function (fn,x,y,z) { return fn(x,y,z); };var sum = function(x,y,z) { return x+y+z;};alert( passFunAndApply(sum,3,4,5) ); // 12


Execute the last alert statement and output a value of 12.

Use functional concepts

The previous section describes some functional programming concepts. The given examples do not contain all concepts, and they are not sequential in terms of importance. They are just some concepts related to this discussion. Below is a quick summary of the functional style in JavaScript:

  • The name is not always required for a function.

  • Functions can be allocated to variables like other values.

  • Function expressions can be written and placed in brackets for future use.

  • Functions can be passed as parameters to other functions.


This section describes some examples of using these concepts to write beautiful JavaScript code. (Using the JavaScript functional style, you can do many things beyond the scope of this discussion .)

  • Extended array sorting

  • Compile a sorting method to sort the data based on the date of the array element. Writing this method in JavaScript is very simple. The Data Object sorting method accepts an optional parameter, which is a comparison function. Here, you need to use the comparison function in listing 11.


    Listing 11. comparison functions

    function (x,y) {return x.date – y.date;}

    To obtain the required function, use the example in listing 12.


    Listing 12. Sorting Function Extension

    arr.sort( function (x,y) {return x.date – y.date; } );


    WhereArrIs a type array object. The sorting function willArrThe date of objects in the array sorts all objects. The comparison function and its definition are passed to the sorting function to complete the sorting operation. Use this function:


    • Each JavaScript Object has a date attribute.

    • The sorting function of the array type in JavaScript accepts optional parameters, which are the comparison functions used for sorting. This is similarqsortFunctions are similar.

  • Dynamically generate beautiful HTML code

  • In this example, we will see how to write beautiful code and dynamically generate HTML from the array. You can generate a table based on the values obtained from the data. Alternatively, you can use the array content to generate a list of sorted and unsorted items. You can also generate a vertical or horizontal menu item.

    The Code style in listing 13 is usually used to generate dynamic HTML from arrays.


    Listing 13. generate common dynamic HTML code

    var str=' ';for (var i=0;i


    You can replace this code with the code in listing 14.


    Listing 14. common methods for generating dynamic HTML

    Array.prototype.fold=function(templateFn) { var len=this.length; var str=' '; for (var i=0 ; i
           


    I useArrayThe prototype attribute defines the new function fold. This function can be used in any array defined later.

  • Application of series Functions

  • Consider the following situation: you want to use a group of functions as the callback function. To achieve this goal, we will usewindow.setTimeoutFunction, which has two parameters. The first parameter is the function called after the second parameter represents the number of milliseconds. Listing 15 shows a way to complete this operation.
    Listing 15. Calling a group of functions in the callback

    window.setTimeout(function(){alert(‘First!');alert(‘Second!');}, 5000);


    Listing 16 shows a better way to complete this operation.


    Listing 16. A better way to call a series of functions

    Function.prototype.sequence=function(g) { var f=this; return function() {  f();g(); }};function alertFrst() { alert(‘First!'); }function alertSec() { alert(‘Second!'); }setTimeout( alertFrst.sequence(alertSec), 5000);


    When processing an event, if you want to call another callback after calling a callback, you can also use the code extension in listing 16. This may be an exercise that you need to complete on your own. Now your interest is ignited.

The above is the content of the beautiful JavaScript_javascript skills written by functional programming technology. For more information, see the PHP Chinese website (www.php1.cn )!

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.