user3271152
user3271152

Reputation: 73

Inner function taking arguments from outer

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     

Upvotes: 7

Views: 105

Answers (2)

AntonKolesnikov
AntonKolesnikov

Reputation: 33

You can use methods call and apply. For examplem, createComparisonFunction.apply(someNewContext, someArguments). First argument for both methods should be context.

Upvotes: 0

Pointy
Pointy

Reputation: 413709

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.

Upvotes: 6

Related Questions