search
HomeWeb Front-endJS TutorialDetailed explanation of js callback function_javascript skills

Making native Apps and Web Apps is now the mainstream, which means that various browser-based web app frameworks are becoming more and more popular, and those doing js are becoming more and more promising. I also decided to gradually move from back-end development to front-end development and mobile development. Without further ado, let’s get to the point of things related to “js callback functions”.

Speaking of callback functions, although many people know what they mean, they still have little understanding. As for how to use it, I'm still a bit confused. Some relevant information on the Internet does not explain in detail what is going on, and the explanation is relatively one-sided. Below I am just talking about my personal understanding, don’t criticize the big guys. Let's take a look at a rough definition: "Function a has a parameter, which is a function b. When function a is executed, function b is executed. Then this process is called callback." This sentence means that function b starts with Function a is passed in as a parameter and executed. The order is to execute a first, and then execute parameter b. b is the so-called callback function. Let's look at the following example first.

Copy code The code is as follows:

function a(callback){
alert('a');
​​ callback.call(this);//or callback(), callback.apply(this), depending on personal preference
}
function b(){
alert('b');
}
//Call
a(b);

This result is that 'a' pops up first, and then 'b' pops up. I guess someone will ask, "What's the point of writing such code? It doesn't seem to have much effect!"

Yes, actually I also think it is meaningless to write like this, "If you call a function, just call it directly in the function." I just wrote a small example for everyone to gain a preliminary understanding. In the actual process of writing code, such parameters are rarely used, because in most scenarios, we have to pass parameters. Here’s one with parameters:

Copy code The code is as follows:

function c(callback){
        alert('c');
​​ callback.call(this,'d');
}
//Call
c(function(e){
alert(e);
});

Does this call look familiar? Here the e parameter is assigned the value 'd'. We simply assign it as a character. In fact, it can also be assigned as an object. Is there an e parameter in Jquery? Let’s talk about it below
How the e parameter in Jquery is assigned by callback.

I think everyone is familiar with the Jquery framework. It has been out for a long time and is used during development. It is relatively simple. It is very convenient to search the API online and it is quick to get started. In the Jquery framework, we sometimes need to obtain some parameters in the event. For example, I want to obtain the coordinates of the current click and the clicked element object. This requirement is easy to handle in Jquery:

Copy code The code is as follows:

           $("#id").bind('click',function(e){
                  //e.pageX, e.pageY, e.target... Various data
        });

It is quite convenient to use. In fact, the assignment of the e parameter is also implemented through the callback function. This parameter is given an object value using the callback parameter. Friends who have carefully studied the JJquery source code should have discovered this.

The same principle applies to the data parameter in Ajax $.get('',{},function(data){}).

Let’s take a look at how the callback function is applied in the Jquery event object.

For the sake of convenience, I simply wrote some implementations related to $. I have written about "Small Talk about Jquery" before, which has a method that is closer to the framework implementation. I will just write a simple selector below.

Copy code The code is as follows:



<script><br />      var   _$=function (id)<br />                { <br />                      this.element=  document.getElementById(id); <br />                 }<br />        _$.prototype={<br />             bind:function(evt,callback)<br />             {<br />                 var   that=this;<br />                 if(document.addEventListener)<br />                 {<br />                     this.element.addEventListener(evt, function(e){<br />                         callback.call(this,that.standadize(e));<br />                     }  ,false);<br />                 }<br />                 else if(document.attachEvent)<br />                 {<br />                     this.element.attachEvent('on' evt,function(e){<br />                         callback.call(this,that.standadize(e));<br />                     });<br />                 }<br />                 else<br />                     this.element['on' evt]=function(e){<br />                         callback.call(this,that.standadize(e));<br />                     };<br />             },<br />             standadize:function(e){<br />                  var  evt=e||window.event;<br />                  var  pageX,pageY,layerX,layerY;<br />                  //pageX  横坐标  pageY纵坐标   layerX点击处位于元素的横坐标   layerY点击处位于元素的纵坐标<br />                  if(evt.pageX)<br />                  {<br />                      pageX=evt.pageX;<br />                      pageY=evt.pageY;<br />                  }<br />                  else<br />                  {<br />                     pageX=document.body.scrollLeft evt.clientX-document.body.clientLeft;<br />                     pageY=document.body.scrollTop evt.clientY-document.body.clientLTop;<br />                 }<br />                  if(evt.layerX)<br />                  {<br />                      layerX=evt.layerX;<br />                      layerY=evt.layerY;<br />                  }<br />                  else<br />                  {<br />                      layerX=evt.offsetX;<br />                      layerXY=evt.offsetY;<br />                  }<br />                  return  {<br />                     pageX:pageX,<br />                     pageY:pageY,<br />                     layerX:layerX,<br />                     layerY:layerY<br />                  }<br />             }<br />        }<br />        window.$=function(id)<br />        {<br />           return  new _$(id);<br />        }<br />         $('container').bind('click',function(e){<br />             alert(e.pageX);<br />         });<br />         $('container1').bind('click',function(e){<br />              alert(e.pageX);<br />         });<br /> </script>

这段代码我们主要看standadize函数的实现,兼容性的代码,就不多说了,返回的是一个对象 

复制代码 代码如下:

     return  {
                    pageX:pageX,
                    pageY:pageY,
                    layerX:layerX,
                    layerY:layerY
                 }

 然后再看bind函数里面的代码    callback.call(this,that.standadize(e)),这段代码其实就是给e参数赋值了,是用callback回调实现的。

callback 函数被调用的时候传入的是匿名函数

复制代码 代码如下:

         function(e){
        }

而callback.call(this,that.standadize(e))相当于是执行了这么一段代码 

复制代码 代码如下:

(함수(e){
          })(표준화(e))

이는 Jquery가 콜백 함수를 사용하는 전형적인 장소이기도 합니다. 이것이 e 매개변수가 할당되는 방식입니다. 이렇게 말하면 이 기능과 사용 방법을 이해할 수 있을 것입니다.

콜백은 다양한 프레임워크에서 널리 사용됩니다. 때로는 직접 작성할 때 실제 상황에 맞게 사용할 수도 있습니다.

Statement
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
Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

See all articles

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version