0

I have following code:

window.$(".my-class").datepicker({
    ...
    onSelect: function() {

        var event = new CustomEvent("input", {});
        this.dispatchEvent(event);
    },
    ...

and it works. But once I change the function to arrow function

window.$(".my-class").datepicker({
    ...
    onSelect: () => {

        var event = new CustomEvent("input", {});
        this.dispatchEvent(event);
    },
    ...

i get error on this saying it doesn't have param dispatchEvent. Why my arrow function has different this?

n1_
  • 4,227
  • 4
  • 34
  • 35
  • Cause arrow functions have no context at all. `this` therefore refers to the function the datepicker code is in, therefore probably being *window* – Jonas Wilms Nov 19 '17 at 11:28
  • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions#No_separate_this – caramba Nov 19 '17 at 11:30
  • I see..strange is when I put a brakepoint into source file in browser devtools and I run the `this.dispatchEvent()` it works. – n1_ Nov 19 '17 at 11:33

1 Answers1

0

In the second case , this refers to the function the datepicker function, not the actual window

if an arrow function appears in the top scope, its this argument will always refer to the global scope, when an arrow function inside a regular function will have its this argument the same as its outer function

Sajeetharan
  • 216,225
  • 63
  • 350
  • 396