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 ?
constructoris 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 ownthiscontext.=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?