Home Web Front-end JS Tutorial Introduction to the use of Javascript high-order functions_javascript skills

Introduction to the use of Javascript high-order functions_javascript skills

May 16, 2016 pm 03:55 PM
javascript higher order function

Higher-order function - If a function receives parameters or returns a function, then we can call this function a higher-order function. As we all know, JavaScript is a weakly typed language: JavaScript functions do not strongly define or type-check input parameters or output values ​​of the function. Then the function can become a parameter or an output value, which embodies the JavaScript Native support for higher-order functions.

1. Higher-order functions whose parameters are functions:

function funcTest(f){  
//简易判断一下实参是否为函数
if((typeof f)==”function”){
f();
}}
funcTest(function(){ });
Copy after login

This is a simple higher-order function that takes parameters as functions. When calling funcTest, input a function as a parameter, and execute the input anonymous function inside funcTest. Of course, such a code snippet has no practical meaning.

1. Higher-order functions whose return values ​​are functions:

function funcTest(){
return function(){};
}
var f=funcTest();
Copy after login

Calling funcTest returns a function.

2. A more complicated example:

//Number类型相加  
function addInt(a,b){
return parseInt(a)+parseInt(b);
 }
//String类型相加
function addString(a,b){
return a.toString()+ b.toString(); 
}  
function add(type){
if(type==="string"){
return addString;
}else{
return addInt; 
}
}
var data1=add("string")("1","2");
//12
var data2=add("int")("1","2");
//3
Copy after login

The above example implements the separation of String type addition and Number type addition. When the add function is called, if the input parameter is "string", a string splicing function is output; if the input parameter is "int", a digital addition function is output.

3. The actual role of higher-order functions:

The above code example basically explains what higher-order functions are. Let’s take a look at how higher-order functions relate to our actual programming:

1, callback function

function callback(value){
alert(value);
}
function funcTest(value,f)
//f实参检测,检查f是否为函数 
if(typeof callback==='function'){
f(value);}}funcTest(‘1',callback);
//1
Copy after login

The example is when funcTest is called, the callback function will be called internally in funcTest, that is, the callback is implemented.

2, Data screening and sorting algorithm

var arr=[0,2,11,9,7,5];
//排序算法
function funcComp(a,b){
if(a<b){
return -1;
}else if(a>b){
return 1;
}else{
return 0;
}
}
//过滤算法
function funcFilter(item,index,array){
return item>=5;
}
//数组顺序排列
arr.sort(funcComp);
alert(arr.join(','));
//0,2,5,7,9,11
//筛选数组
var arrFilter=arr.filter(funcFilter);
alert(arr.join(‘,'))
//5,7,9,11
Copy after login

3, DOM element event definition

<html><title></title>
<body><input type=”button” value=”ClickMe” id=”myBtn” >
<script type=”text/javascript>
var btnClick=document.getElementById(“myBtn”);
//测试环境为FireFox
btnClick. addEventListener(“click”,function(e){
alert(“I'm a button!”);
//I'm a button},false);
</script>
</body>
</html>
Copy after login

In the above example, a button with the id myBtn is defined in the document, and the js script adds a click event to it, where the second parameter of addEventListener is a function.

Conclusion: High-order functions are not a patent of JavaScript, but they are definitely a powerful tool for JavaScript programming. Higher-order functions are actually a re-abstraction of basic algorithms. We can use this to improve the abstraction of the code, achieve maximum code reuse, and write code that is simpler and more conducive to refactoring.

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

How to implement an online reservation system using WebSocket and JavaScript How to implement an online reservation system using WebSocket and JavaScript Dec 17, 2023 am 09:39 AM

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

How to get HTTP status code in JavaScript the easy way How to get HTTP status code in JavaScript the easy way Jan 05, 2024 pm 01:37 PM

Introduction to the method of obtaining HTTP status code in JavaScript: In front-end development, we often need to deal with the interaction with the back-end interface, and HTTP status code is a very important part of it. Understanding and obtaining HTTP status codes helps us better handle the data returned by the interface. This article will introduce how to use JavaScript to obtain HTTP status codes and provide specific code examples. 1. What is HTTP status code? HTTP status code means that when the browser initiates a request to the server, the service

How to use insertBefore in javascript How to use insertBefore in javascript Nov 24, 2023 am 11:56 AM

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

See all articles