Is there any reason to write classic syntax of ES6 methods?
class MyClass {
myMethod() {
this.myVariable++;
}
}
When I use myMethod()
as callback on some event, I must write something like this (in JSX):
// Anonymous function.
onClick={() => { this.myMethod(); }}
// Or bind this.
onClick={this.myMethod.bind(this)}
But if I declare method as arrow function:
class MyClass {
myMethod = () => {
this.myVariable++;
}
}
than I can write just (in JSX):
onClick={this.myMethod}
Unlike regular functions, arrow functions do not have their own this . The value of this inside an arrow function remains the same throughout the lifecycle of the function and is always bound to the value of this in the closest non-arrow parent function.
Unlike regular functions, arrow functions do not have their own this . Arguments objects are not available in arrow functions, but are available in regular functions. Regular functions created using function declarations or expressions are 'constructible' and 'callable'.
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.
An arrow function doesn't have its own this value and the arguments object. Therefore, you should not use it as an event handler, a method of an object literal, a prototype method, or when you have a function that uses the arguments object.
The feature you are using is not part of ES6. It's the class fields proposal. It allows you to initialize instance properties without having to write a constructor. I.e. your code:
class MyClass {
myMethod = () => {
this.myVariable++;
}
}
is exactly the same as
class MyClass {
constructor() {
this.myMethod = () => {
this.myVariable++;
};
}
}
And this also shows you what the difference is between a normal class method an a method created via a class field:
So all the same as reasons as presented in Use of 'prototype' vs. 'this' in JavaScript? apply, but in short:
this
also only works if you are using an arrow function.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