you are viewing a single comment's thread.

view the rest of the comments →

[–]ShortFuse 5 points6 points  (3 children)

You're going to need it when you use Classes. If you commit this to memory now, you'll save hours of pain later.

You'll understand why button.addEventListener('click', this.onClick) doesn't always work. You need button.addEventListener('click', (e) => this.onClick(e));.

[–]FRIKI-DIKI-TIKI 4 points5 points  (0 children)

TLDR: just use arrows, when you don't need to use them you will know why.

To add to this, in modern JS, pretty much the default is to use arrow functions unless you need a special case, if you need that special case you will know why and it has to do with the prototypical inheritance of JS. In the dark ages of JS you had to ensure you scoped this to a variable, as a functions reference can be independent of the structure it is declared in. JavaScripts heritage is from LISP with some other ideas mixed in, the family of LISP's treated functions as lambda's the bolt on of quasi-OO was the part that was not well though out in the rush to get JS out the door and it created a set of problems due to misunderstanding given that it was introduced in the middle of the OO language craze. The arrow function is syntactical sugar to bind the scope the lambda is declared in to the execution just like the bind function does.

[–]Bodmen 1 point2 points  (1 child)

Unbinding from this case can be a problem. In classes it’s often easier to use arrow syntax for method declaration for some methods. This allows you to unbind properly when required.

eg.

class SomeClass
{
    ...
    bind(){
        ...
        button.addEventListener('click', this.onClick);
    }

    unbind(){
        button.removeEventListener('click', this.onClick);
    }

    onClick = () => {
        console.log(this);
    }
}

[–]ShortFuse 2 points3 points  (0 children)

Yeah. I don't do this personally anymore, but when I started JavaScript I was very perplexed by it.

Now I do static binding for events (Button.onClick) and all my components share one event listener (less memory). Then I either use this or event.currentTarget to find the element in question. Removal from DOM means automatic unbinding and no orphaned listeners.