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.
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());
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With