Can someone explain how Babel in React supports fat arrow functions as class properties? Using Babel Try it out I can see they are not supported:
class Question {
// Property (not supported)
myProp = () => {
return 'Hello, world!';
}
// Method (supported)
myFunc() {
return 'Hello, world!';
}
}
Class properties are not supported in ES6 (correct me if I'm wrong) but then in React (with Babel) they work.
I can see the difference between methods and properties using TypeScript Playground but I can't clearly understand if Babel is supporting them or not. Is there some plug-in?
UPDATE:
I can see they are supported using "babel-preset-stage-0"
.
You should avoid using arrow functions in class as they won't be the part of prototype and thus not shared by every instance. It is same as giving the same copy of function to every instance.
Regular functions created using function declarations or expressions are constructible and callable. Since regular functions are constructible, they can be called using the new keyword. However, the arrow functions are only callable and not constructible, i.e arrow functions can never be used as constructor functions.
What is @babel/plugin-proposal-class-properties? This plugin transforms static class properties as well as properties declared with the property initializer syntax.
An arrow function expression is an anonymous function expression written with the “fat arrow” syntax ( => ). Like traditional function expressions, arrow functions are not hoisted, and so you cannot call them before you declare them. They are also always anonymous—there is no way to name an arrow function.
To support class properties, you need to install and add babel-plugin-transform-class-properties
to the plugins
setting of your .babelrc
(or in your webpack
config).
Note that this plugin is also included in
babel-preset-stage-0
babel-preset-stage-1
babel-preset-stage-2
So if you use one of those, you don't need to install babel-plugin-transform-class-properties
by yourself.
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