Property initializer syntax in ESnext
Asked Answered
Q

2

7

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;
  }
}
Quickfreeze answered 4/6, 2017 at 20:26 Comment(2)
Because it's a property, and not a class method, you can bind this to the function, which the arrow function does automatically.Scleritis
Àrrow function vs. traditional function...Normy
E
6

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.

Enginery answered 4/6, 2017 at 20:30 Comment(0)
H
0

From a different angle, you can use the Property initializer syntax as a shorthand for otherwise verbose method binding in constructor.

Also notice that the syntax can be used for variables as well.

class Property {
  v = 42

  bar = () => {
    return this.v
  }
}
// --------

class Bound {
  constructor() {
    this.v = 43
    this.bar = this.bar.bind(this)
  }

  bar() {
    return this.v;
  }
}
// --------

class Classic {
  constructor() {
    this.v = 44
  }

  bar() {
    return this.v;
  }
}

,

const allBars = [
  new Property().bar,
  new Bound().bar,
  new Classic().bar
]

console.log([
  allBars[0](),
  allBars[1](),
  allBars[2]()
])

// prints: [42, 43, undefined]

Property v is undefined in the allBars array where the this of unbound bar points since it was called from its context.

Heigho answered 11/9, 2017 at 17:56 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.