Home > Web Front-end > JS Tutorial > Miscellaneous talk about callback functions, anonymous functions, and closures

Miscellaneous talk about callback functions, anonymous functions, and closures

高洛峰
Release: 2016-11-21 14:11:11
Original
1128 people have browsed it

Callback function

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

Imagine you order 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 they will call you when it arrives.

It is easy to see that the second solution is a more efficient solution. In fact, when this notification mechanism is applied to the programming field, it is a 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 do we need a callback function

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 languages ​​such as c and c++, 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, an anonymous function is passed for calling The logical processing after success 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 it brings are not just reduced coding.

Closure

In programming technology, closure should be a more advanced technology. When using callback functions, it usually involves passing 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 the user information. The that variable is assigned by var that = this, so the variable points to the app object itself, so it can succeed. Save user information.

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. The app object needs to be passed to the callback function (global variable or function parameter), and with the support of closure technology, the callback function can access that variable just like using the internal variable of the function, which is much more convenient in syntax.


Related labels:
js
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template