Document directory
- 1. modular and reusable code
- 2. Event Handler
Introduction
Do you know that JavaScript is actually a functional programming language? This guide will teach you how to use the functional features of JavaScript.
Requirement: You should 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 few documents mention the functional features of JavaScript. In this guide, I will only explain this basic knowledge without going deep into other functional languages or Lambda operators.
You can click all the examples and the code you see will be executed, so that the Guide will become interactive. You can also try this sandbox.
Lesson 1: anonymous Functions
Lesson 2-function as Value
Lesson 3-two methods to call a function
Lesson 4-short circuit condition call
Lesson 5-where is it?
JavaScript Programming original address: http://www.pfeiffer-mediation.de/remast/javascript.php Translation: ShiningRay
Introduction to functional JavaScript programming guide
Do 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 because there is too much information about JavaScript programming, but very few documents mention the functional features of JavaScript. In this guide, I will only explain this basic knowledge without going deep into other functional languages or Lambda operators.
You can click all the examples and the code you see will be executed, so that the Guide will become interactive. You can also try this sandbox.
Lesson 1: anonymous Functions
We will first introduceAnonymous Functions. An anonymous function is a function without a name.
You can think of them as disposable functions. They are especially useful when you only need to use a function once. By using anonymous functions, there is no need to keep the functions in the memory, so using anonymous functions is more efficient.
Example:
The following two functions process the same thing, whileAverageInZThe value is retained after the assignment is completed-but the anonymous function does 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 the next lesson.Function as Value.
Lesson 2-function as Value
In fact, we generally declare functions in JavaScript as a simplified syntax (that isSyntactic sugar,Syntactic sugar).
Example:
The following two expressions are actually exactly the same. Therefore, the expression on the left is only 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) );
Here we can draw a conclusion that a function is a value just like a string, number, or array. There are also several problems:
-
Can I pass functions as parameters?
-
Yes. See the example below.
-
Can functions be generated in real time?
-
Of course, this is an advanced topic. EvalFunction.
TIPS:Check the source code on 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-two methods to call a function
In JavaScript, there are two methods to call functions. The general method is to put the parameters in brackets, suchAlert (42). Another way is to put both functions and parameters in brackets, as shown in(Alert) (42).
Example:
alert(42);
(alert) (42);
(function(x) { alert(x-13); }) (55);
The brackets on both sides of the function are important:If you write parentheses, the code in the brackets will be calculated first. After 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 4-short circuit condition call
Now we will learn how to use the "Short Circuit" condition to call. This method can shorten the source code and make the code 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-where is it?
OK. Now we have learned some functional JavaScript content. So where is it? Functional JavaScript programming has three main reasons:
- It helps write modular and usable code.
- It is very effective for event handlers.
- It's interesting!
In the following sections, I will provide more information about the first two reasons.
1. modular and reusable code
Now that you know how to use a function as a value, you should also try it! A good example is the built-in arraySortMethod. PredefinedSort ()Convert all objects into strings and sort them by words. However, if we have a user-defined object or number, it is not very useful. So this function allows you to give him a comparison function as a parameter, suchSort (compareFunction). This method makes us not even 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; };myarray.sort(sortDesc);alert(myarray);myarray.sort(sortAsc);alert(myarray);
2. Event Handler
Functional Programming for event handlers may be the most intuitive function to be applied. In this case, we will immediately demonstrate an example.
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"); });
Press me!
Exercise:Why should weAlertWrapped in an anonymous function?
Advanced example:
Now we want to improve our Button class. Each button is assigned a value that is displayed when the button is clicked. First, 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 middle of the prompt box is empty. Why? The reason is the JavaScript Visibility rules. When the onclick function is executedThisIt points to the DOM node of the button rather than the Custom button object.
How can we solve this problem?Function programming:
this.button.onclick = (function(v) { return function() { alert(v); }; }) (this.value);
In this case, executing the anonymous function willVBindThis. value.
Sandbox
<Br/> alert (42); <br/>
[Ctrl + A select all Note: If you need to introduce external Js, You need to refresh it to execute]
More information
Below are some interesting links to functional JavaScript programming:
- W3future.com-function programming for event processing and callback Functions
- Svendtofte.com-practical (& functional) JavaScript code snippet
- Svendtofte.com-Excellent JavaScript Library (includingMap,Fold,...)
- CodingForums-a more theoretical article on functional JavaScript using Lambda Operators
- Lambda tutorial-tutorial on coding Lambda operators in JavaScript
- The Little JavaScripter-Comparison Between Scheme and JavaScript
Outlook
This section describes the future of JavaScript. A very exciting JavaScript feature --E4X, Directly supported by XML in JavaScript.
- Wikipedia on E4X-a good introduction to E4X
- Mozilla E4X-Brandon Eich (Mozilla chief architect) demonstration of E4X