Hey.

Consider an example.

var heights = []; // переменная, которая будет хранить высоты элементов $("div").each(function(indx, element){ heights.push($(element).height()); }); // в итоге, в переменную heights будут помещены значения высот всех div-элементов 

It should be noted that the this variable, inside the callback function, will store the same value as the second domElement parameter that is passed to it. Thus, the previous example could look like this:

 var heights = []; // переменная, которая будет хранить высоты элементов $("div").each(function(indx){ heights.push($(this).height()); }); // в итоге, в переменную heights будут помещены значения высот всех div-элементов 

The question is - WHY the this variable, inside the callback function, will store the same value as the second domElement parameter that is passed to it?

this refers to the object in which the function lies. I do not understand WHERE this anonymous function lies (in which object it is nested). If I deal with a regular function, then I know WHERE I declared it (within which object), respectively, I know where the this property will refer to when it goes to work out the local function code.

  • Possible duplicate question: Lost call context - Grundy
  • @ Jean-Claude, at least two links in the comments above. - Grundy
  • I still do not understand - Dimon
  • one
    @Dimon, because it is necessary to read in the question / answers by reference, how the context is determined (the value of this inside the function) the function has and what it depends on. And then you should look into the jQuery source and notice that callback is called using the call function - Grundy

1 answer 1

Because the Function object in JavaScript has a call method, by calling which you can pass any this function to the function.

  • one
    Yes, and bind ....... but it seems he is not talking about it - Jean-Claude
  • @ Jean-Claude, yes, bind is not about that, it connects the context with the function, but does not call it - Grundy