better understanding of callback functions in javascript
I am reading this function in a book, and I don't understand how the anonymous function is pass开发者_Go百科ed the thirst three arguments?
This is what I understand
function multiplyByTwo(a, b, c, callback) {
var i, ar = [];
for(i = 0; i < 3; i++) {
ar[i] = callback(arguments[i] * 2);
}
return ar;
}
but not this
myarr = multiplyByTwo(1, 2, 3, function(a){return a + 1});
thanks, Richard
Some comments detailing the contract of the multiplyByTwo
function would be helpful here:
// multiplyByTwo
// num num num (num -> x) -> x[]
function multiplyByTwo(a, b, c, callback) {
...
This means that the function takes four arguments, and returns an array of x
. x
can be any type. The first three arguments are numbers. The fourth argument to the function is actually a function itself. This function takes a number, and returns an x
. Again, x
can be any type, but it is the same type throughout the contract.
Inside the multiplyByTwo
function, the callback function is called once for each of the other arguments. The result of each of these calls is added to an array, which is the return value of multiplyByTwo
.
The arguments
variable is a special variable in javascript, which, inside the scope of a function, gives access to all of the arguments to that function, as an array.
The callback function is bound to the name callback
in the scope of the multiplyByTwo
function. It can then be called as any other function, such as by appending parentheses and arguments. The anonymous function that you gave when you called multiplyByTwo
can then be referenced by that name.
So, in the example given, multiplyByTwo
is called with four arguments: 1
, 2
, 3
, and an anonymous function. Inside the scope of the multiplyByTwo
function, these arguments are bound to the variables a
, b
, c
, and callback
, respectively. These arguments can also be referenced through the special arguments
array. In the example, both methods are used to reference the arguments. The first three are referenced using the arguments
array inside a loop, and the fourth argument is referenced using its name, as in callback(...)
.
The anonymous function is called 3 times in the loop, each time passing in a different argument. The first time it passes in arguments[0]
, which is a
(and arguments[1]
would be b
, etc.). arguments
is a property of the currently executing function and refers to the parameters passed into the function. In JavaScript, you don't have to name your parameters, or access them by their names, or even pass in all of the named parameters.
精彩评论