user11524995
user11524995

Reputation:

Can arrow functions be used in ES6 class defenitions?

Can arrow functions technically be used in ES6 class definitions? I am not asked if they should be, but if they can be?

I was curious after reading his MDN article said they were ill suited as methods.

If so what is the proper syntax?

class someComponent extends React.Component {
  constructor(props) {
    super(props);
   }

  // arrow function here

  render () {
  }
}

Research

Currying with Arrow Functions

Upvotes: 2

Views: 163

Answers (1)

Michael Sorensen
Michael Sorensen

Reputation: 2124

From my understanding there is not a proper syntax because an arrow function does not provide any benefit. However, if you were wondering how you might include an arrow function inside your class well... Here you go:

class someClass {
  constructor() {
    this.myTestProperty = "fus ro dah";
    this.someArrowMethod = () => {
      console.log("Arrow Method: ", this.myTestProperty);
    };
  }

  method() {
    console.log("Normal Method: ", this.myTestProperty);
  }

  //ERROR: this is illegal in node v10 but webpack or typescript may be able to compile it correctly. 
  illegalArrowMethod = () => {

  }
}

const something = new someClass();

something.method();
something.someArrowMethod();

As you can see the correct class Object's properties are still available via the this keyword inside the normal Method. So I can't think of a use case why you would use an arrow function inside your class.

Upvotes: 2

Related Questions