ESnext syntax initializer syntax

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

I have not yet found a lot of documentation for this, but it is used in the egghead course when discussing React.

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

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

class Foo {
  bar() {
    return this;
  }
}
+4
source share
2 answers

When you use the property initializer syntax with an arrow, thisthis function will always refer to an instance of the class, while using ordinary methods you can change thisusing .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
Run code

, , .

+4

Property verbose .

, .

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]

v undefined allBars, this bar , .

0

Source: https://habr.com/ru/post/1678519/


All Articles