I don't get how the inner function gets passed the arguments from .sort() method.
I know that .sort() passes the values to createComparisonFunction(), but how do they end up in the inner function? Does it just take any unused arguments from the outer function?
I'd like to understand that behavior.
function createComparisonFunction(propertyName) {
return function(object1, object2){
var value1 = object1[propertyName];
var value2 = object2[propertyName];
if (value1 < value2){
return -1;
} else if (value1 > value2){
return 1;
} else {
return 0;
}
};
}
var data = [{name: "Zachary", age: 28}, {name: "Nicholas", age: 29}];
data.sort(createComparisonFunction("name"));
alert(data[0].name); //Nicholas
data.sort(createComparisonFunction("age"));
alert(data[0].name); //Zachary
Python Inner Functions or Nested Functions can access the variables of the outer function as well as the global variables.
The structure of a function begins with an equal sign (=), followed by the function name, an opening parenthesis, the arguments for the function separated by commas, and a closing parenthesis.
A parameter is a named variable passed into a function. Parameter variables are used to import arguments into functions. For example: function example(parameter) { console.
No, the .sort() function does not pass parameters to "createComparisonFunction". Instead, "createComparisonFunction" does exactly what its name suggests: it creates a function and returns it. The returned function is the one called repeatedly by the .sort() method.
Note that in the call to .sort():
data.sort( createComparisonFunction("name") );
the "createComparisonFunction" is being called. That's what the parenthesized argument list (with the single parameter "name") means — call this function. That happens before the runtime invokes the .sort() method. What's passed to .sort() is the return value, which is itself a function.
The most interesting thing going on is that the returned function — which takes two parameters, as a sort comparator should — has access to the parameter originally passed to "createComparisonFunction". That's because a function that's returned from another function retains access to its original creation-time local variable context.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With