0
function comParison(propertyName){
    return function(obj1,obj2){
       var value1 = obj1[propertyName];
       var value2 = obj2[propertyName];

       if (value1 < value2){
        return -1;
       }else id (value1 > value2){
        return1;
       }else{
        return 0;
       }
    }
  };


var data = [{name:n1},{name:n2}];
data.sort(comParison("name"));

this will compare name, but how does comParison function access name property and why it have to pass as string?

jfriend00
  • 683,504
  • 96
  • 985
  • 979
enix
  • 113
  • 1
  • 8
  • 1
    Go checkout associative array in Javascript. That should help. – anuj_io Jul 07 '13 at 17:11
  • @tea_totaler What is an _"associative array"_ in _JavaScript_? Do you mean an _Object_ or an _Array_ of _Objects_? – Paul S. Jul 07 '13 at 17:30
  • *" how does comParison function access name property"* like so: `obj1[propertyName]`. That's called *bracket notation*. *"why it have to pass as string"* because it would not work otherwise. – Felix Kling Jul 07 '13 at 17:55
  • Because it's [bracket notation](http://stackoverflow.com/questions/4968406/javascript-property-access-dot-notation-vs-brackets). – Bergi Jul 07 '13 at 20:18

1 Answers1

0

Above example is based on closures. Step by step it's roughly like this:

  1. comParison function accepts propertyName as an argument
  2. Anonymous function created inside comParison, that function has access to propertyName and everything else inside comParison (and global variables).
  3. This anonymous function is then returned as a sorting function
  4. By the time this anonymous function is called it still has access to propertyName variable due to closure, and is, therefore, able to access obj[propertyName]

Hope this makes it a bit clear.

Another useful answer.

Community
  • 1
  • 1
mishik
  • 9,973
  • 9
  • 45
  • 67