27

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.

Shan Robertson
  • 2,742
  • 3
  • 25
  • 43
  • I'd typically have a 'var self = this' just inside Foo, but it feels equally as nasty. But remember, JavaScript isn't an OO language. – Ian Oct 01 '15 at 17:45
  • The article [ECMAScript 6: automatically binding extracted methods](http://www.2ality.com/2013/06/auto-binding.html) presents 2 solutions. – Ori Drori Oct 01 '15 at 17:48
  • Try using a fat arrow function for watch: `watch() {() => {console.log(this)} }` – Brian Glaz Oct 01 '15 at 17:53
  • @OriDrori proxies have only been implemented in recent FF and MS Edge and are not (and I would think, could not) polyfilled by transpilers. – Jared Smith Oct 01 '15 at 17:55
  • @BrianGlaz: They are called "arrow functions", not "fat arrow functions". – Felix Kling Oct 01 '15 at 18:52
  • @FelixKling https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions – Brian Glaz Oct 01 '15 at 18:54
  • @BrianGlaz: http://www.ecma-international.org/ecma-262/6.0/index.html#sec-arrow-function-definitions ... "fat arrow function" comes from CoffeeScript, but it's not an *official* term in JavaScript. Makes sense, since there is no "thin arrow function". – Felix Kling Oct 01 '15 at 18:55

2 Answers2

25

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());
Roy Miloh
  • 3,381
  • 1
  • 18
  • 17
1

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.

D. Melo
  • 2,139
  • 2
  • 14
  • 19