javascript - 可以在 ES6 类定义中使用箭头函数吗?
问题描述
箭头函数在技术上可以在 ES6 类定义中使用吗?没有人问我是否应该这样做,但是否可以?
在阅读了他的MDN 文章后我很好奇他们是ill suited as methods
.
如果是这样,正确的语法是什么?
class someComponent extends React.Component {
constructor(props) {
super(props);
}
// arrow function here
render () {
}
}
研究
解决方案
据我了解,没有正确的语法,因为箭头函数没有任何好处。但是,如果你想知道如何在你的类中包含一个箭头函数......你去:
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
普通方法中的关键字获得。所以我想不出一个用例为什么你会在你的类中使用箭头函数。
推荐阅读
- laravel - 重定向到 laravel nova 应用程序中的自定义工具 url
- c++ - 有理由不使用最新的 C++ 标准吗?
- react-native - React native - 当用户关闭应用程序时执行一个功能
- javascript - 无法读取未定义的属性“setAttribute”
- mongodb - 在 Github 存储库中使用 MongoDB 连接字符串
- ffmpeg - 如何在没有 CPU 完整解码的情况下从 h264 中提取运动矢量
- amazon-web-services - 亚马逊网络服务。使用哪些?
- mysql - 生成变量的所有组合并插入临时表
- python - Selenium python google地址侧边栏结果
- firebase - 解析触发器时出错:找不到模块“firebase-admin/lib/database”