【发布时间】:2018-06-03 23:29:52
【问题描述】:
我是使用 ES6 类和 React 的新手,以前我一直将我的方法绑定到当前对象(在第一个示例中显示),但是 ES6 是否允许我将类函数永久绑定到带有箭头的类实例? (在作为回调函数传递时很有用。)当我尝试像使用 CoffeeScript 一样使用它们时遇到错误:
class SomeClass extends React.Component {
// Instead of this
constructor(){
this.handleInputChange = this.handleInputChange.bind(this)
}
// Can I somehow do this? Am i just getting the syntax wrong?
handleInputChange (val) => {
console.log('selectionMade: ', val);
}
因此,如果我将SomeClass.handleInputChange 传递给例如setTimeout,它将被限定为类实例,而不是window 对象。
【问题讨论】:
-
我很想知道 TypeScript 的相同答案
-
TypeScript 的解决方案与 ES7 提案相同(参见accepted answer)。这由 TypeScript 原生支持。
-
对于所有在这里结束的人来说,这是一个有趣的阅读主题"arrow functions in class properties might not be as great as we think"
-
你应该避免在类中使用箭头函数,因为它们不是原型的一部分,因此不会被每个实例共享。这与给每个实例提供相同的函数副本相同。
-
@SourabhRanka 在构造函数中添加
this绑定也不行吗?
标签: javascript arrow-functions ecmascript-next class-fields