Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

es6 classes and "this" with event handlers [duplicate]

playing around with some es6 and ran into an issue i'm not sure how to solve. consider the following

class Foo {
 constructor ( ) {
   window.addEventListener('scroll', this.watch);
 }

 watch ( ) {
   console.log(this);
 }
}

Inside of watch, this is the window object, as expected. But how do i refer to Foo? Currently I get around this with bind this.watch.bind(this) but i'd love to know if there is a more "proper" ES6 way to get this going.

like image 699
Shan Robertson Avatar asked Oct 01 '15 17:10

Shan Robertson


2 Answers

You can use arrow function.

An arrow function expression (also known as fat arrow function) has a shorter syntax compared to function expressions and lexically binds the this value.

window.addEventListener('scroll', () => this.watch());
like image 116
Roy Miloh Avatar answered Nov 16 '22 14:11

Roy Miloh


The class keyword is just a syntatic sugar for the known javascript prototype inheritance chain. The way the this attribution mechanism works is the same. Just keep thinking about the class as the good old function what works with this, so it can be attributed to the one that used the new keyword.

E6 comes with lots of new keywords to make object oriented javascript more familiar. I'm happy with that but we all must remember that the fundamental parts are still the same, just now with some shadows for newcomers :D

Ps: Given that you know how this is defined in Javascript, you can use it without an alias, like self or something like that, despite that beeing a common practice.

like image 20
D. Melo Avatar answered Nov 16 '22 15:11

D. Melo