Monday, May 20, 2024
9
rated 0 times [  11] [ 2]  / answers: 1 / hits: 16299  / 9 Years ago, thu, october 1, 2015, 12:00:00

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.


More From » ecmascript-6

 Answers
8

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());

[#64871] Tuesday, September 29, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
alonso

Total Points: 747
Total Questions: 108
Total Answers: 105

Location: Mauritania
Member since Sun, Sep 25, 2022
2 Years ago
;