Home > Web Front-end > JS Tutorial > Completely master the js callback function

Completely master the js callback function

小云云
Release: 2018-03-16 16:30:14
Original
1758 people have browsed it


1. Prelude

Before talking about the callback function, let’s take a look at the following two pieces of code:
You might as well guess the result of the code.

function say (value) {
    alert(value);
}alert(say);alert(say('hi js.'));
Copy after login

If you test it, you will find:

Just write the variable name say and what will be returned will be the say method itself, expressed in the form of a string.
Adding () after the variable name such as say() will return the result after the say method is called. Here is the value of the pop-up value.

2. Functions in js can be passed as parameters

Look at the following two pieces of code:

function say (value) {
    alert(value);
}function execute (someFunction, value) {
    someFunction(value);
}
execute(say, 'hi js.');
Copy after login

and

function execute (someFunction, value) {
    someFunction(value);
}
execute(function(value){alert(value);}, 'hi js.');
Copy after login

The first piece of code above is Pass the say method as a parameter to the execute method
The second piece of code directly passes the anonymous function as a parameter to the execute method

Actually:

function say (value) {
    alert(value);
}// 注意看下面,直接写say方法的方法名与下面的匿名函数可以认为是一个东西
// 这样再看上面两段代码是不是对函数可以作为参数传递就更加清晰了say;function (value) {
    alert(value);
}
Copy after login
这里的say或者匿名函数就被称为回调函数。
Copy after login

3. The callback function is easy to confuse Click - Pass parameters

If the callback function needs to pass parameters, how to do it? Here are two solutions.

  • Pass the parameters of the callback function as parameters of the same level as the callback function

Completely master the js callback function

  • The parameters of the callback function are created inside the calling callback function

Completely master the js callback function

##Related recommendations:

javascript callback Detailed explanation of function (callback)

Events and callback functions of JavaScript running mechanism

PHP callback function concept and usage

The above is the detailed content of Completely master the js callback function. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
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