首页 > 解决方案 > 可以在 ES6 类定义中使用箭头函数吗?

问题描述

箭头函数在技术上可以在 ES6 类定义中使用吗?没有人问我是否应该这样做,但是否可以?

在阅读了他的MDN 文章后我很好奇他们是ill suited as methods.

如果是这样,正确的语法是什么?

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

  // arrow function here

  render () {
  }
}

研究

使用箭头函数进行柯里化

标签: javascriptecmascript-6

解决方案


据我了解,没有正确的语法,因为箭头函数没有任何好处。但是,如果你想知道如何在你的类中包含一个箭头函数......你去:

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

正如您所看到的,正确的类 Object 的属性仍然可以通过this普通方法中的关键字获得。所以我想不出一个用例为什么你会在你的类中使用箭头函数。


推荐阅读