How is it legal to use a function name as the argument to another function in JavaScript?
I was gearing up for Javascript, reading the tutorials at W3Schools and came across this code:
function sortNumber(a, b)
{
return a - b;
}
var n = ["10", "5", "40", "25", "100", "1"];
document.write(n.sort(sortNumber));
It sorts the elements in t开发者_开发知识库he Array, pretty simple. But how can we pass sortNumber
( a function name) as a parameter to the sort function?
But how can we pass sortNumber ( a function name) as a parameter to the sort function?
Functions are first-class objects in JS and can be passed around as parameters or variables. Are you clear how the sort itself is working?
Surprisingly, JavaScript has its roots in a language called Scheme.
Scheme allows certain functions (called 'lambda functions') to be passed around as though they were a variable.
JavaScript handles functions in much the same way scheme did. (Some people say that "functions are first-class-citizens in JavaScript.")
For example, you can write:
// Assign a function to foo
var foo = function () { alert('bar'); };
// Call foo like a function
foo();
The result would be that the message 'bar' is shown.
The classic example of lambdas is the "Adder" example:
adder = function (x) {
return function (y) {
x + y
}
};
add5 = adder(5);
add5(1); // == 6
Hope this helps.
If you look at the documentation for the sort
function within Javascript, the parameter that it accepts, which is optional is a function that can be used to determine the sort.
The function returns a positive, negative or zero value allowing the sort function to determine where everything needs to go.
You're actually passing a reference to the function itself, not its name. If you were passing its name, you would enclose it in quotes like this: "sortNumber".
sort() (as the documentation says) takes an optional argument which specifies the sorting function.
Functions are first class citizens in javascript.
Sort can take an optional paramater, a function that returns a -1, 0 or 1(whether a greater, equal to or lessthan b)
Using a-b returns a positive, zero or negative number, to do this.
The answer is available on W3Schools as well : http://www.w3schools.com/jsref/jsref_sort.asp
the Array sort() method takes one parameter which is a function handler.
A variable in javascript can contain a anytype of value, that includes functions. If you use the name of the function without the parenthesis, your referencing the function, and not actually calling it.
精彩评论