Reputation: 55769
I understand there is a TC-39 proposal for a new syntax called "property initializer syntax" in JavaScript class
es.
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;
}
}
Upvotes: 7
Views: 2368
Reputation: 31997
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.
Upvotes: 0
Reputation: 92619
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.
Upvotes: 6