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;
}
}
The new class “property initializers” allows you to define methods (or any property) in your React components using regular ES6 classes without worrying about binding.
esnext is a JavaScript library for converting JavaScript written using the ES6 draft specification syntax to JavaScript that will work today.
Objects can be initialized using new Object() , Object. create() , or using the literal notation (initializer notation). An object initializer is a comma-delimited list of zero or more pairs of property names and associated values of an object, enclosed in curly braces ( {} ).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With