简体   繁体   中英

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     

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM