1

I wonder there is a difference between...

document.addEventListener('DOMContentLoaded', function() { callback() });

and

document.addEventListener('DOMContentLoaded', callback);

I've seen code like this, and I'm curious as to why they put the function inside an anonymous function.

var on_load = function(f) {
  if (document.body === null)
    document.addEventListener('DOMContentLoaded', function() { f() }, false)
  else
    f()
}
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
YiJisol
  • 45
  • 3
  • 1
    Related: https://stackoverflow.com/a/59878788 – VLAZ Oct 02 '21 at 08:24
  • Whenever you have function(...args) { fn(...args) }, as a parameter of other function, just provide fn. It will be working fine in both cases, but do it "right way" – DraganS Oct 02 '21 at 09:18
  • Does that mean that `addEventListener('event', callback)` is more recommended than `addEventListener('event', function() { callback() })`? – YiJisol Oct 02 '21 at 10:47
  • @YiJisol *in this case* it's the same and this it can be eta-reduced. Whether it's "more recommended" is opinion-based. I'd use the first version myself. Others might prefer the latter, as it's easier to refactor to add parameters to it. Many probably wouldn't care. – VLAZ Oct 02 '21 at 12:39

1 Answers1

0

There is a clear difference. This first example is pretty useless, because the callback function is being deprived of the event argument:

document.addEventListener('DOMContentLoaded', function() { callback() });

whereas this one:

document.addEventListener('DOMContentLoaded', callback);

provided that the value of callback is a function, will be called with the event as the first argument and with the element whose event handler is handling the event, as the this-argument.

So if you had asked what is the difference between:

document.addEventListener('DOMContentLoaded', function() { callback.apply(this, arguments) });

versus this one:

document.addEventListener('DOMContentLoaded', callback);

then the answer is: nothing but one extra indirection.

Gunther Schadow
  • 1,490
  • 13
  • 22