Better functional JavaScript Programming Guide Tutorials _javascript Tips

Source: Internet
Author: User
Tags anonymous

Did you know that JavaScript is actually a functional programming language? This guide will teach you how to use the functional features of JavaScript.

Requirements: You should have a basic understanding of JavaScript and DOM.

The purpose of writing this guide is that there is too much information about JavaScript programming, but there is very little information about the functional nature of JavaScript. In this guide, I will only explain these basics without delving into other functional languages or this is a lambda operator.

You can click on all the examples and the code you see will be executed so that the guide becomes interactive. You can also use this sandbox to try.

First lesson--anonymous function

We will first introduce anonymous functions . An anonymous function is a function that has no name.
You can think of them as a one-time function. They are especially useful when you need to use only one function at a time. By using anonymous functions, it is not necessary to keep functions in memory, so using anonymous functions is more efficient.

Example Example:

The following two functions handle the same thing, andaverage在给z赋值结束之后一直保留——但匿名函数则不会。

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

This naturally leads us to the following lesson function as a value .

Lesson two-functions as values

In fact, the way we generally declare functions in JavaScript can be seen as a simplified syntax (i.e., syntactic sugars ,syntactic sugar).

Cases:

The following two expressions are actually exactly the same. So the expression on the left is just the shorthand on the right.
function average (x,y) {return 
 (x+y)/2; 
} 
Alert (average (1,3)); 
var average = function (x,y) {return 
 (x+y)/2; 
} 
Alert (average (1,3)); 

From here you can conclude that a function is a value like a string, a number, or an array. There are several problems:

Can I pass the function as a parameter?
OK, see the example below.
Can I generate a function in real time?
of course, it's an advanced topic, it can be done eval函数来完成。 小提示:看看本页面的源代码。 by

Cases:

This example demonstrates how to pass a function as a parameter.

var applyfun = function (f,x,y) {return F (x,y);}; 

var add = function (x,y) {return 
 x+y; 
}; 

Alert (Applyfun (add,3,4)); 7 

Lesson number three-two ways to call a function

In JavaScript, there are two ways to call a function. The general way is to put the parameters in parentheses, such asalert(42)。另一种方式是同时把函数和参数都放在括号中,如(alert)(42)。

Cases:

Alert (42); 

(alert) (42); 
(function (x) {alert (x-13);}) (55); 

why the parentheses on both sides of the function are important: If you write parentheses, the code in parentheses is evaluated first. After the calculation, there is a value in the place where the parentheses are located. This value may be a string, a number, or a function.

Lesson four-"short-circuit" condition call

Now we'll learn how to use a "short-circuit" condition call. Use this method to shorten the source code and the code becomes more readable.

Cases:

This syntax is not used on the left expression, but on the right expression.

var f = false; var t = True;var Z; 
if (f) 
 z = 4; 
else if (t) 
 z = 2; 
alert (z); 

var f = false; var t = true; 
var z = (f && 4) | | (t && 2); 
alert (z); 

Lesson five-where is it?

OK, now we've learned some of the content of functional JavaScript. So where is it? Functional JavaScript programming is important for three main reasons:
    1. It helps write code that is modular and can be taken.
    2. It is very effective for event handlers.
    3. It's funny!
In the following pages, I'll give you more information on the first two reasons.

1. Modular and reusable Code

Now that you know how to use a function as a value, you should try it too! A good example is the array built insort方法。预定义的sort()把所有的对象转换成字符串并把他们按照词语的顺序排序。但如果我们有用户自定义的对象或者数字那么它就不是很有用了。于是这个函数可以让你给他一个进行比较的函数作为参数,如sort(compareFunction)。这个方法让我们甚至不用接触实际的sort方法。

Cases:

var myarray = new Array (6,7,9,1,-1); 
var sortasc = function (x,y) {return x-y;}; 
var sortdesc = function (x,y) {return y-x;}; 
Myarray.sort (SORTDESC); 
alert (myarray); 

Myarray.sort (SORTASC); 
alert (myarray); 

2. Event handlers

Using functional programming with event handlers may be the most intuitive function that is worth applying. So we'll show you an example right now.

Simple example:; IE

Now there is a button class with a custom onclick behavior.

function Button (clickfunction) { 
  This.button = document.createelement ("button"); 
  This.button.appendChild (document.createTextNode ("Press me!")); 
  This.button.onclick = clickfunction; 
} 
var bt = new Button (function () {alert ("42");}); 

Practice: Why do we have to putalert包裹在一个匿名函数中?

Advanced Examples:

Now we want to improve our button class. Each button is assigned a value button to display when clicked. First we adjust our class:

function Button (value) { 
  this.value = value; 
  This.button = document.createelement ("button"); 
  This.button.appendChild (document.createTextNode ("Test")); 
} 

Below you may try to write the following code:

 
This.button.onclick = function () {alert (this.value);}; 

If you execute it you will find that the Tip box is empty in the middle. Why is that? The reason for this is JavaScript's visibility rules. When the onclick function is executedthis指向的是按钮的DOM节点而非自定义的按钮对象。

How can we solve this problem? Using functional Programming:

This.button.onclick = (function (v) {return 
      function () {alert (v);}; 
      }) (This.value); 

In this case, executing the anonymous function willv绑定到this.value上。

Sand box

Enter your code here and press the calculation .

alert (a);

More information

Here are some interesting links to functional JavaScript programming:

    • W3future.com-Functional programming for event-handling functions and callback functions
    • Svendtofte.com-Useful (& functional) JavaScript snippets
    • Svendtofte.com-an excellent JavaScript library (includingmap, fold, …)
    • Codingforums-a more theoretical article on functional JavaScript using lambda operators
    • Lambda Tutorial-tutorial on encoding lambda operators in JavaScript
    • The Little Javascripter-a comparison between Scheme and JavaScript

Prospect

This section shows you the future of JavaScript. A very exciting JavaScript feature--e4x, a direct XML support in JavaScript.

    • Wikipedia on e4x-a good introduction to E4X
    • Mozilla E4x-brandon Eich (Mozilla chief architect) demo on e4x
This entry is written by Shiningray, posted on 2008-01-02 at 22:jan, filed under Translation and tagged JavaScript, functional Process. The permalink of the Bookmark. Follow any comments the RSS feed to this post. Post a comment or leave a trackback:trackback URL.
--> -->
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.