0

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 ?

3
  • 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 with testEmpty, though. Also, arrow functions have no own this context. Commented May 5, 2019 at 14:34
  • 1
    The syntax of class members initialized with = is not an ES2015 (ES6) feature. Those are instance fields, and are implemented as if they were this.x = y; initialization statements in the constructor. Commented May 5, 2019 at 14:36
  • Also, why is it that you want => functions as methods? What would you be able to do if you could use them? Commented May 5, 2019 at 14:37

1 Answer 1

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().

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.