Table of Contents
Callback function
Why a callback function is needed
Anonymous function
Closure
Home WeChat Applet Mini Program Development Basics of WeChat Mini Program Development: Callback Functions, Anonymous Functions, and Closures (4)

Basics of WeChat Mini Program Development: Callback Functions, Anonymous Functions, and Closures (4)

Apr 25, 2017 am 09:25 AM

Strictly speaking, this is not a WeChat applet tutorial, but I will use the app.js code in the previous article as an example, so let’s just make it count.

Callback function

The callback function may be a little difficult to understand for students who are new to programming. After all, the use of callback functions is contrary to the intuitive process of program sequence execution.

Imagine that you have ordered a takeout. One way is to check whether the takeout has arrived regularly. The other way is to show your phone number to the delivery person and call you when it arrives.

It is easy to see that the second solution is more efficient. In fact, when this notification mechanism is applied to the programming field, it is callback function.

Students who are familiar with win32 development should know that a typical windows program framework is a message loop plus a window procedure function. The windows system takes over the message acceptance, and then calls the developer's window procedure function to complete the specific message processing logic. The window procedure function is a callback function.

Why a callback function is needed

Take the above win32 program as an example. We know that for security reasons, the Windows operating system does not allow developers to directly access hardware resources. Microsoft developers provide an API to handle the message loop, but the response logic for specific messages needs to be provided by the developer. In this case, the callback function is a good implementation solution.

To give another example, imagine that you are involved in the development of a mobile phone device management software project, and you are responsible for the underlying device communication module. When the user inserts the device into the computer, you need to notify the upper-level module to process it. For the sake of flexibility and versatility, it is impossible for you to put the processing logic when the device is connected in the module you are responsible for. At this time, the upper-level caller can provide a callback function, and your module calls the callback function when the device is connected. That’s it.

Regarding callback functions, there is a so-called Hollywood criterion: Don't call me; I'll call you!

Anonymous function

In c, c++ and other languages, when you need to use a callback function, you need to pre-define a function body. The callback function is usually only provided to other modules for calls. In order to simplify coding, subsequent scripting languages ​​​​such as JavaScript provide support for anonymous functions. (Note: The new C++ standard has also begun to support anonymous functions, called Lambda functions)

getUserInfo:function(cb){
    var that = this
    if(this.globalData.userInfo){
      typeof cb == "function" && cb(this.globalData.userInfo)
    }else{
      //调用登录接口
      wx.login({
        success: function () {
          wx.getUserInfo({
            success: function (res) {
              that.globalData.userInfo = res.userInfo
              typeof cb == "function" && cb(that.globalData.userInfo)
            }
          })
        }
      })
    }
  },
Copy after login

The above code comes from app.js in the previous tutorial. When calling wx.login, a The anonymous function performs logical processing after the call is successful, which is the part after success. You can see that there is only a function definition but no function name, so except as a callback function, the function cannot be called elsewhere.

In fact, anonymous functions are just a coding simplification, but the benefits they bring are not just reduced coding.

Closure

In programming technology, closure should be a more advanced technology.
When using callback functions, it usually involves the passing of some context. In languages ​​such as c/c++, global variables or heap memory are used to pass context. The disadvantages of global variables are obvious, and heap memory is prone to memory leaks. In more advanced scripting languages, context transfer can be easily accomplished through closure technology.

Taking the above code as an example, that.globalData.userInfo = res.userInfo is executed in the callback function to save user information. The that variable is assigned by var that = this, so the variable points to the app object itself. , so the user information can be saved successfully.

We can see that the that object is a variable on the getUserInfo method stack. Without closure technology, the anonymous callback function here cannot directly use the that variable, so the app object needs to be passed to the callback function ( Global variables or function parameters), and with the support of closure technology, the callback function can access that variable just like using internal variables of the function, which is much more convenient in syntax.

The above is the detailed content of Basics of WeChat Mini Program Development: Callback Functions, Anonymous Functions, and Closures (4). For more information, please follow other related articles on the PHP Chinese website!

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

Video Face Swap

Video Face Swap

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

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)

What is the meaning of closure in C++ lambda expression? What is the meaning of closure in C++ lambda expression? Apr 17, 2024 pm 06:15 PM

In C++, a closure is a lambda expression that can access external variables. To create a closure, capture the outer variable in the lambda expression. Closures provide advantages such as reusability, information hiding, and delayed evaluation. They are useful in real-world situations such as event handlers, where the closure can still access the outer variables even if they are destroyed.

Usage and characteristics of C++ anonymous functions Usage and characteristics of C++ anonymous functions Apr 19, 2024 am 09:03 AM

An anonymous function, also known as a lambda expression, is a function that does not specify a name and is used for one-time use or to pass a function pointer. Features include: anonymity, one-time use, closures, return type inference. In practice, it is often used for sorting or other one-time function calls.

How to implement closure in C++ Lambda expression? How to implement closure in C++ Lambda expression? Jun 01, 2024 pm 05:50 PM

C++ Lambda expressions support closures, which save function scope variables and make them accessible to functions. The syntax is [capture-list](parameters)->return-type{function-body}. capture-list defines the variables to capture. You can use [=] to capture all local variables by value, [&] to capture all local variables by reference, or [variable1, variable2,...] to capture specific variables. Lambda expressions can only access captured variables but cannot modify the original value.

What are the advantages and disadvantages of closures in C++ functions? What are the advantages and disadvantages of closures in C++ functions? Apr 25, 2024 pm 01:33 PM

A closure is a nested function that can access variables in the scope of the outer function. Its advantages include data encapsulation, state retention, and flexibility. Disadvantages include memory consumption, performance impact, and debugging complexity. Additionally, closures can create anonymous functions and pass them to other functions as callbacks or arguments.

The impact of function pointers and closures on Golang performance The impact of function pointers and closures on Golang performance Apr 15, 2024 am 10:36 AM

The impact of function pointers and closures on Go performance is as follows: Function pointers: Slightly slower than direct calls, but improves readability and reusability. Closures: Typically slower, but encapsulate data and behavior. Practical case: Function pointers can optimize sorting algorithms, and closures can create event handlers, but they will bring performance losses.

Chained calls and closures of PHP functions Chained calls and closures of PHP functions Apr 13, 2024 am 11:18 AM

Yes, code simplicity and readability can be optimized through chained calls and closures: chained calls link function calls into a fluent interface. Closures create reusable blocks of code and access variables outside functions.

Can Golang anonymous functions return multiple values? Can Golang anonymous functions return multiple values? Apr 13, 2024 pm 04:09 PM

Yes, anonymous functions in Go language can return multiple values. Syntax: func(arg1,arg2,...,argN)(ret1,ret2,...,retM){//Function body}. Usage: Use the := operator to receive the return value; use the return keyword to return multiple values.

How are closures implemented in Java? How are closures implemented in Java? May 03, 2024 pm 12:48 PM

Closures in Java allow inner functions to access outer scope variables even if the outer function has exited. Implemented through anonymous inner classes, the inner class holds a reference to the outer class and keeps the outer variables active. Closures increase code flexibility, but you need to be aware of the risk of memory leaks because references to external variables by anonymous inner classes keep those variables alive.

See all articles