Search code examples
jqueryfirefoxconsoleeachgreasemonkey-4

What happens to 'this' between two calls of .each()?


The following code in a GM script in FF 68.0.1:

let input = $( 'input#id' );

input.each( function(){console.debug(this)} );
input.each( debugn(this) );

function debugn( message ) {
  console.debug(message)
}

prints first:

<input id="id" ...>

as expected but then:

Sandbox { browser: {...

Even if the internal iterator is consumed at the first call and not initialised at the second (though .each() doesn't mention such a behaviour) it shouldn't print the Sandbox object but simply not call debugn(...), shouldn't it?


Solution

  • It's not about the fact that you're calling the .each method twice it's how you're calling it each time.

    The first time you call an anonymous function which in turn calls the console.debug method and passes this as the argument.

    The second time, you pass your debugn function as the argument to the each function which in turn calls the console.debug method but the context of this has changed because you passed your function in directly as the argument of the each function.

    Short answer: the way you did it first is the way Jquery wants you to do it. If you have a named function you want to call, just call it inside an anonymous function much like how you did the first time

    input.each( function(){
      debugn(this)
    } );