Do you know that JavaScript is actually a functional programming language? This guide will teach you how to take advantage of the functional features of JavaScript.
Require:You should already have a basic understanding of JavaScript and DOM.
The purpose of writing this guide is because there is too much information about JavaScript programming, but very little information mentions the functional features of JavaScript. In this guide, I will only explain these basics without digging 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, which will make the guide interactive. You can use this tooSandboxCome and try it.
Lesson 1 - Anonymous Functions
We will first introduceAnonymous functions. An anonymous function is a function without a name.
You can think of them as one-time functions. They are especially useful when you only need to use a certain function once. By using anonymous functions, there is no need to keep the functions in memory all the time, so using anonymous functions is more efficient.
Example:
The following two functions handle the same thing, andaverageGivingzIt remains after the assignment is finished - but anonymous functions do not.
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 to our next lessonFunction as value。
Lesson 2 - Functions as Values
In fact, the way we declare functions in JavaScript can be regarded as a simplified syntax (that is,Syntactic sugar,syntactic sugar)。
example:
The following two expressions are actually exactly the same. So the expression on the left is just the abbreviation 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 this we can draw a conclusion that a function is a value like a string, a number, or an array. There are several more problems:
- Can I pass the function as an argument?
- Yes, see the example below.
- Is it possible to generate functions in real time?
- Of course, this is a high-level theme, it can be done throughevalFunction to complete.Tips:Check out the source code of this page.
example:
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 3 - Calling functions in two ways
In JavaScript, there are two ways to call functions. The general way is to put parameters in brackets, such asalert(42). Another way is to put both functions and parameters in brackets, such as(alert)(42)。
example:
alert(42);
(alert) (42);
(function(x) { alert(x-13); }) (55);
Why parentheses on both sides of a function are important:If you write brackets, the code in the brackets will be calculated first. After calculation, there will be a value where the brackets are located. This value may be a string, a number, or a function.
Lesson 4 - "Short Circuit" Condition Call
Now we will learn how to use the "short-circuit" conditional call. Use this method to shorten the source code and the code becomes more readable.
example:
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 5 - What's good about it
OK, now we have learned some functional JavaScript content. So what's good about it? There are three main reasons why functional JavaScript programming is very important:- It helps write modular and acceptable code.
- It is very effective for event handlers.
- It's very fun!
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 built-in arrayssortmethod. Predefinedsort()Convert all objects into strings and sort them in the order of words. But if we have user-defined objects or numbers then it is not very useful. So this function allows you to give him a function that compares it as a parameter, such assort(compareFunction). This method allows us to not even have to touch the actualsortmethod.
example:
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; }; (sortDesc); alert(myarray); (sortAsc); alert(myarray);
2. Event handler
Using functional programming for event handlers is perhaps the most intuitive function as worth applying. In this case, we will demonstrate an example immediately.
Simple example:;ie
There is now a Button class with a custom onclick behavior.
function Button(clickFunction) { = ("button"); (("Press me!")); = clickFunction; } var bt = new Button(function() { alert("42"); });
practise:Why do we need toalertWrapped in an anonymous function?
Advanced examples:
Now we want to improve our Button class. Each button is assigned a value to display the value when the button is clicked. First we adjust our class:
function Button(value) { = value; = ("button"); (("test")); }
Here you might want to try writing the following code:
= function() { alert(); };
If you execute it you will find that the middle of the prompt box is empty. Why is this happening? In fact, the reason lies in the visibility rules of JavaScript. When the onclick function is executedthisPoints to the DOM node of the button rather than a custom button object.
How do we solve this problem?Using functional programming:
= (function(v) { return function() { alert(v); }; }) ();
Executing the anonymous function in this case willvBind tosuperior.
Sandbox
More information
Here are some interesting links about functional JavaScript programming:
- - Functional programming for event handling and callback functions
- - Practical (& functional) JavaScript code snippets
- - Excellent JavaScript library (includingmap, fold, …)
- CodingForums- A more theoretical article about functional JavaScript using Lambda operator
- Lambda tutorial- Tutorial on encoding Lambda operators in JavaScript
- The Little JavaScripter- aboutSchemeComparison between JavaScript
Outlook
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 (Chief Architect of Mozilla) Demonstration on E4X