Search code examples
javascriptecmascript-next

Property initializer syntax in ESnext


I understand there is a TC-39 proposal for a new syntax called "property initializer syntax" in JavaScript classes.

I haven't yet found much documentation for this, but it is used in an egghead course when discussing React.

class Foo {
  bar = () => {
    return this;
  }
}

What is the purpose of this proposal? How does it differ from:

class Foo {
  bar() {
    return this;
  }
}

Solution

  • When you use property initializer syntax with an arrow function, this in this function will always refer to the instance of the class, whereas with regular methods, you can change this by using .call() or .bind():

    class Foo {
      constructor() {
        this.test = true;
      }
      bar = () => {
        return this;
      }
    }
    console.log(new Foo().bar.call({}).test); // true
    
    class Foo2 {
      constructor() {
        this.test = true;
      }
      bar() {
        return this;
      }
    }
    console.log(new Foo2().bar.call({}).test); // undefined

    Also, this syntax can be used for other things than functions.