lang/js/ BindingClassMethods


Public Class Field Functions instead of Class Methods

See this at mozilla and can I use for compatibility information.

If you have e.g.

class A {
  constructor() {
    window.addEventListener("resize",this.resize)
  }
  resize() {
    console.log(this)
  }
}

then resize() would show that this === window, not the A instance. In earlier versions of Javascript, you had to put this in your constructor:

  constructor() {
    window.addEventListener("resize",this.resize)
    this.resize = this.resize.bind(this)
  }

and doing this for every method gets annoying quickly. In newer versions of Javascript, you can instead just do

  resize = () => {
    ..
  }

and when resize is invoked, it will capture the value of this from when the constructor was running, which is what we generally want.