Callback
What is the callback function: in plain vernacular, it is a function of the way to pass parameters passed to another function call then this function is called a callback function
to look at a small example in JQuery:
$('#btn').click(function(){
console.log(1)
})
上述代码我们将一个匿名函数作为参数传递给了`click`方法。`click`方法会调用(或者执行)我们传递给它的函数。这是`Javascript`中回调函数的典型用法,它在`jQuery`中广泛被使用。
Let's look at a typical Javascript callback function example:
let arr = ['Russ','James','Harden']
arr.forEach(function(name,index){
console.log(index + 1 + '.' + name)
})
注意,我们又一次将一个匿名函数以参数的方式传给了`forEach`方法
So far, we have two forms of anonymous function as a parameter passed to another method. In the future we see more examples or write our own code when we need to look at in the end is how the callback function to run
The callback function operating principle
Because functions are first-class objects in Javascript, we treat the same treatment as a function of the object, so we can pass transfer function like a variable, function return in the function, use the function in other functions. ※ When we pass a callback function as a parameter to another function, we just passed the function definition. We did not perform the function in the argument. We do not pass like we usually perform the same function with a pair of functions to perform parentheses () ※ The
note is very important that the callback function will not be executed immediately, this anonymous function will be called later in the body of the function, as follows:
let arr = ['Russ','James','Harden']
arr.forEach(function(name,index){
console.log(index + 1 + '.' + name)
})
Callback functions are also closures
When we pass a callback function as an argument to another function, the callback function contains some point in the execution of its functions, as if the callback function is included as it is defined in the function. This means that the callback function is essentially a closure.
As we know, the closure can include visiting scope of its functions, therefore callback function can get it included in the variable, and the variables in global scope.
The basic principle to achieve callback
In fact, implement a callback function is not difficult, but before you begin to realize and create a callback function, be familiar with the basic principles of the callback function several implementations.
Use a named or anonymous function as callback
In jQuery examples and examples of previous forEach, we use the anonymous function parameter and then position defined as the callback function. This is a common magic in the callback function in use. Another common pattern is to define a named function and function name passed to the function as a variable. Such as the following examples:
let allUserName = []
function logName(data){
if(typeof data === 'String' ){
console.log(data)
}else if(typeof data === 'Object'){
for(let item in data){
console.log(data[item])
}
}
}
function getData(options,callback){
allUserName.push(options)
callback(options)
}
getData({name1:"Russ",name2:"Harden"},logName)
Let's create a function called logName
normal function, is a function of the conditions inside the name of the output in the console. Then we create a function called getData
ordinary function, this function accepts two parameters, the first value is passed, the second callback function. When we call getData
time method, we function logName
as a callback to pass getData
, so in getData
the course of implementation, logName
will be called back inside
Parameters passed to the callback function
let name3 = "James"
funcrtion getData(options,callback){
allUserName.push(options)
callback(name3,options)
}
既然回调函数在执行时仅仅是一个普通函数,那么我们就能给它传递参数。我们能够传递任何包含它的函数的属性(或者全局属性)作为回调函数的参数
Use this object method as a callback function problems
When the callback function is a method for this object, we must change the method of performing the callback function to ensure that the context of this object. Otherwise, if passed to the callback function is a global function, this points to the global window object or objects, or points to an object that contains the method.
let clientData = {
id: 100101,
fullName: "",
setUserName:function(firstName,lastName){
this.fullName = fiestName + " " + lastName
}
}
function getData(firstName,lastName,callback){
//doing someting
callback(firstName,lastName)
}
Because the function getData
is a global function, then it this
points to window
an object, so clientData.setUserName
when executed as a callback function, this.fullName
and can not accurately pointing to clientData
the fullName
variable, but it is equivalent to the window
next target adds a named fullName
field.
getData("Russell","Westbrook",clientData.setUserName)
console.log(clientData.fullName) //""
console.log(window.fullName) //Russell Westbrook
Use Call and Apply to save this function
We all know that JavaScript
in every function has two known call
and apply
methods, their role is used to change the this
point of, their differences will not speak here.
apply method:
function getData(firstName,lastName,callback,callbackObj){
//doing someting
callback.apply(callbackObj,[firstName,lastName])
}
We have added new callback object as a parameter called callbackObj
. We'll clientData.setUserName
methods and clientData
object as a parameter, clientData
the object will be Apply
use to set this
an object
using the Apply
method set correctly this
point, we are now correctly execute the clientData.setUserName
callback function and clientData
object set correctly fullName
attribute
getData("Russell","Westbrook",clientData.setUserName,clientData)
console.log(clientData.fullName) //Russell Westbrook
Callback Hell
What is a callback hell: it is generally to javaScript
the execution order to write code, when executing asynchronous code, no matter in what order simple code execution, usually become many levels callback accumulation
Solution: 1. abandon the use of anonymous functions , to all functions named in the name of the callback functions manner; 2. concise code; 3 module children of the repeated code into a body function; 4.promise