View Single Post
  #1 (permalink)  
Old February 14th, 2016, 03:47 PM
MrAnalogy MrAnalogy is offline
Registered User
Points: 8, Level: 1
Points: 8, Level: 1 Points: 8, Level: 1 Points: 8, Level: 1
Activity: 0%
Activity: 0% Activity: 0% Activity: 0%
 
Join Date: Feb 2016
Posts: 2
Thanks: 0
Thanked 0 Times in 0 Posts
Default How does the return function in createComparisonFunction() get it's parameters?

On line 4 a function is declared which is RETURNED to the calling function.

How do Object1 and 2 get defined/set?

This is from Chapter 5 of Professional javascript... 3rd edition.


Code:
 <script type="text/javascript">
            function createComparisonFunction(propertyName) {
            
                return function(object1, object2){
                    var value1 = object1[propertyName]; //how do Object1 and object2 get set?
                    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        
    
        </script>
Reply With Quote