Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inner function taking arguments from outer

Tags:

javascript

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     
like image 259
user3271152 Avatar asked Feb 04 '14 14:02

user3271152


People also ask

Can an inner function access outer variable?

Python Inner Functions or Nested Functions can access the variables of the outer function as well as the global variables.

What separates the arguments inside a function?

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.

What do you call a arguments that pass value inside the function?

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.


1 Answers

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.

like image 109
Pointy Avatar answered Oct 04 '22 23:10

Pointy