Study notes on callback functions in js_javascript skills
What is a callback function? Before learning, I really didn’t know how to use and function the js callback function. In this article, I will introduce the example of the callback function that I am learning to the students. Students who need to know more can refer to it for reference.
Principle of callback function:
I’m leaving now and I’ll let you know when I arrive”
This is an asynchronous process. During the process of "I go" (function execution), "you" can do anything. "Arrived" (function execution completed) "notify you" (callback) after the process
Example
1.Basic method
<script language="javascript" type="text/javascript"> function doSomething(callback) { // … // Call the callback callback('stuff', 'goes', 'here'); } function foo(a, b, c) { // I'm the callback alert(a + " " + b + " " + c); } doSomething(foo); </script>
Or use anonymous function form
<script language="javascript" type="text/javascript"> function dosomething(damsg, callback){ alert(damsg); if(typeof callback == "function") callback(); } dosomething("回调函数", function(){ alert("和 jQuery 的 callbacks 形式一样!"); }); </script>
2. Advanced methods
Use the call method of javascript
<script language="javascript" type="text/javascript"> function Thing(name) { this.name = name; } Thing.prototype.doSomething = function(callback) { // Call our callback, but using our own instance as the context callback.call(this); } function foo() { alert(this.name); } var t = new Thing('Joe'); t.doSomething(foo); // Alerts "Joe" via `foo` </script>
Pass parameters
<script language="javascript" type="text/javascript"> function Thing(name) { this.name = name; } Thing.prototype.doSomething = function(callback, salutation) { // Call our callback, but using our own instance as the context callback.call(this, salutation); } function foo(salutation) { alert(salutation + " " + this.name); } var t = new Thing('Joe'); t.doSomething(foo, 'Hi'); // Alerts "Hi Joe" via `foo` </script>
Use javascript’s apply to pass parameters
<script language="javascript" type="text/javascript"> function Thing(name) { this.name = name; } Thing.prototype.doSomething = function(callback) { // Call our callback, but using our own instance as the context callback.apply(this, ['Hi', 3, 2, 1]); } function foo(salutation, three, two, one) { alert(salutation + " " + this.name + " – " + three + " " + two + " " + one); } var t = new Thing('Joe'); t.doSomething(foo); // Alerts "Hi Joe – 3 2 1" via `foo` </script>
Example
//If the data source provided is an integer, which is the score of a certain student, when num<=0, it will be processed by the bottom layer, and when n>0, it will be processed by the high-level layer.
//Copy the following function and save it as 1.js
function f(num,callback){ if(num<0) { alert("调用低层函数处理!"); alert("分数不能为负,输入错误!"); }else if(num==0){ alert("调用低层函数处理!"); alert("该学生可能未参加考试!"); }else{ alert("调用高层函数处理!"); callback(); } }
//Save the following test.html file and 1.js in the same directory:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=gb2312"> <script src="1.js" type="text/javascript"></script> <title>无标题文档</title> <script type="text/javascript"> function test(){ var p=document.getElementById("pp"); pp.innerText=""; var num=document.getElementById("score").value; f(num,function(){ //匿名高层处理函数 if(num<60) alert("未及格!"); else if(num<=90) alert("该生成绩优良!"); else alert("该生成绩优秀!"); }) pp.innerText="by since1978 qq558064!" } </script> </head> <body> <p> 回调函数示例:当学生成绩score<=0分时候,由底层处理;当score>0时,由高层处理。 </p> 请输入学生成绩<input type="text" id="score"> <input type="button" onClick="test()" value=" 看看结果"> <p id="pp"></p> </body> </html>
The following are additions from other netizens:
Callback mode in javascript:
looks like:
function writeCode(callback){ //执行一些事物, callback(); //... } function intrduceBugs(){ //....引入漏洞 } writeCode(intrduceBugs);
We pass the application of the function to writeCode() and let writeCode execute it at the appropriate time (called after returning)
Let’s look at a not-so-good example first (it will be reconstructed later):
//模拟查找页面中的dom节点,将查找到的节点存在数组里面统一返回 //此函数只用于查找不对dom节点做任何的逻辑处理 var findNodes = function(){ var i = 100000;//大量的循环, var nodes = [];//用于存储找到的dom节点 var found; while(i){ i -=1; nodes.push(found); } return nodes; } //将查找找到的dom节点全部隐藏 var hide = function(nodes){ var i = 0, max = nodes.length; for(;i<max;i++){ //findNodes后面有括号代表立即执行,先执行findNodes()然后执行hide()< hide(findNodes()); 执行函数 } ; nodes[i].style.display="none" } 上面的方法是低效的,以为hide()必须再次遍历有findNodes()返回的数组节点,如何避免这种多余的循环呢。 我们不能直接在findNodes中对查询到的节点进行隐藏(这样检索就可修改逻辑耦合了),那么他就不再是一个通用函数了。 解决方法是用回调模式,可以将节点隐藏逻辑以回调函数方式传递给findNodes()并委托其执行 //重构findNodes以接受一个回调函数 var findNodes = fucntion(callback){ var i = 100000, nodes = [], found; //检查回调函数是否可用调用的 if(typeof callback !== 'function'){ callback = false; } while(i){ i -= 1; if(callback){ callback(found); } nodes.push(found); } return nodes; } //回调函数 var hide = function(node){ node.style.display = 'none '; } //找到后续节点并在后续执行中对其进行隐藏 findNodes(hide);//先执行findNodes然后执行hide,当然回调函数也可以在调用主函数时创建:findNodes(function(node){node.style.display = 'none';});

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



The writing methods of java callback function are: 1. Interface callback, define an interface, which contains a callback method, use the interface as a parameter where the callback needs to be triggered, and call the callback method at the appropriate time; 2. Anonymous inner class callback , you can use anonymous inner classes to implement callback functions to avoid creating additional implementation classes; 3. Lambda expression callbacks. In Java 8 and above, you can use Lambda expressions to simplify the writing of callback functions.

Introduction to the basic writing and usage of Java callback functions: In Java programming, the callback function is a common programming pattern. Through the callback function, a method can be passed as a parameter to another method, thereby achieving indirect call of the method. The use of callback functions is very common in scenarios such as event-driven, asynchronous programming and interface implementation. This article will introduce the basic writing and usage of Java callback functions, and provide specific code examples. 1. Definition of callback function A callback function is a special function that can be used as a parameter

Vue component communication: using callback functions for component communication In Vue applications, sometimes we need to let different components communicate with each other so that they can share information and collaborate with each other. Vue provides a variety of ways to implement communication between components, one of the common ways is to use callback functions. A callback function is a mechanism in which a function is passed as an argument to another function and is called when a specific event occurs. In Vue, we can use callback functions to implement communication between components, so that a component can

Application of Java callback function in event-driven programming Introduction to callback function A callback function is a function that is called after an event or operation occurs. It is commonly used in event-driven programming, where the program blocks while waiting for an event to occur. When the event occurs, the callback function is called and the program can continue execution. In Java, callback functions can be implemented through interfaces or anonymous inner classes. An interface is a mechanism for defining function signatures that allows one class to implement another class's

Using the database callback function in Golang can achieve: executing custom code after the specified database operation is completed. Add custom behavior through separate functions without writing additional code. Callback functions are available for insert, update, delete, and query operations. You must use the sql.Exec, sql.QueryRow, or sql.Query function to use the callback function.

Callback functions are one of the concepts that every front-end programmer should know. Callbacks can be used in arrays, timer functions, promises, and event handling. This article will explain the concept of callback functions and help you distinguish between two types of callbacks: synchronous and asynchronous.

Analysis of common callback function application scenarios in Python requires specific code examples. A callback function refers to passing a function as a parameter to another function in programming, and executing this parameter function when a specific event occurs. Callback functions are widely used in asynchronous programming, event processing, GUI programming and other fields. This article will analyze common callback function application scenarios in Python and give relevant specific code examples. Asynchronous Programming In asynchronous programming, callback functions are often used to handle the results of asynchronous tasks. When it is necessary to execute a consumption

Function pointers and callback functions are both tools for implementing the callback mechanism. Function pointers are created at compile time and cannot be modified and need to be called explicitly; callback functions are created at runtime and can be dynamically bound to different functions and automatically called by the callback function. Therefore, function pointers are suitable for static callbacks, while callback functions are suitable for dynamic callbacks.
