D
D
Daniil Igorevich2016-01-27 17:00:14
JavaScript
Daniil Igorevich, 2016-01-27 17:00:14

Where does the function get its variables from?

var users = [{
  name: "Вася",
  surname: 'Иванов',
  age: 20
}, {
  name: "Петя",
  surname: 'Чапаев',
  age: 25
}, {
  name: "Маша",
  surname: 'Медведева',
  age: 18
}];


function byField(field){
  return function (a,b){
    return a[field] > b[field] ? 1 : -1;
  }
}

users.sort(byField('name'));
users.forEach(function(user) {
  alert( user.name );
});

This code works, but where does the nested function in the byField function take the variables a and b if for byField = window, and for the nested function - byField(). Does where the function is called from affect the ? After all, somehow a and b with sort() were passed to byField()

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey, 2016-01-27
@Petr_Anisimov

but where does the nested function in the byField function take the variables

you call the sort function and give it this "nested" function as an argument. Functions in JS are the same objects as numbers, strings, etc.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question