1

In a previous question, I was encouraged to ask this follow up: What difference does it make to wrap a function some.func into something like (arg) => some.func(arg) if I know that some.func only takes one argument?

As a concrete example: In my other question I observed a surprising difference between using

.on("mouseover", tip.show)

versus

.on("mouseover", (d) => tip.show(d))

In this case the first version did have the expected behavior, while the second version was behaving differently (see jsfiddle of other question). The reason here was that I accidentally made tip a global.

The more general question: Why do they behave differently in the first place?

Community
  • 1
  • 1
bluenote10
  • 16,847
  • 7
  • 76
  • 133

2 Answers2

3

When you use tip.show(d), that function will be called passing tip as the this value.

When you use tip.show as the event listener, it will be called with the current event target as the this value.

var obj = {checkThis: function(e) {
  console.log(this === e.currentTarget, this === obj);
}};
document.body.addEventListener('click', obj.checkThis);         // true, false
document.body.addEventListener('click', e => obj.checkThis(e)); // false, true
document.body.click();
Oriol
  • 225,583
  • 46
  • 371
  • 457
2

There are two major differences.

We would need to see more context to determine which of these applied in this case.

this

The value of this inside the show function depends on how the function is called.

If the event handler is the function itself, then this is the object on which the event handler is bound.

If the event handler is a function that calls tip.show, then this is tip.

Further reading: How does the “this” keyword work?

Timing

In one case the value of tip.show is evaluated when the event handler is registered.

In the second, the value is evaluated when the event handler is triggered.

Community
  • 1
  • 1
Quentin
  • 800,325
  • 104
  • 1,079
  • 1,205