I was wondering to know if I can write a pure ES6 class using arrow functions. Here is my class example:
class PhoneNumber {
constructor(phoneNumber) {
this.phoneNumber = phoneNumber;
}
testEmpty() {
if (!this.phoneNumber) return true;
return false;
}
}
Doen't seem that I can write it as:
class PhoneNumber {
constructor = phoneNumber => {
this.phoneNumber = phoneNumber;
}
testEmpty = () => {
if (!this.phoneNumber) return true;
return false;
}
}
Altough I can write something similar on React:
class PhoneNumber extends React.Component {
state = {
phoneNumber: this.props.phoneNumber;
}
testEmpty = () {
if (!this.state.phoneNumber) return true;
return false;
}
}
Why React component, even being a class, accepts the ES6 arrow function and my pure class doesn't ?
1 Answer 1
Constructor cannot be an arrow function at all. You can create arrow methods in react because react uses proposals for class fields under the hood. You can add them to your project with babel proposal plugins. The benefit of using arrow class methods is that value of this in such a method would refer to class itself inside a callback. So you can use arrow methods inside of an event listener without wrapper function or without bind().
Comments
Explore related questions
See similar questions with these tags.
constructor
is not a variable or function name, but a language-specifig keyword. Therefore, you can't "define" it as an arrow function.It should work withtestEmpty
, though. Also, arrow functions have no ownthis
context.=
is not an ES2015 (ES6) feature. Those are instance fields, and are implemented as if they werethis.x = y;
initialization statements in the constructor.=>
functions as methods? What would you be able to do if you could use them?