【发布时间】:2017-05-13 21:33:00
【问题描述】:
在创建 React 类时,哪个更可取?
export default class Foo extends React.Component {
constructor (props) {
super(props)
this.doSomething = this.doSomething.bind(this)
}
doSomething () { ... }
}
或
export default class Foo extends React.Component {
doSomething = () => { ... }
}
我的一个同事认为后者会导致内存问题,因为 babel 将代码转换为在闭包内捕获 this,并且该引用将导致实例不被 GC 清理。
对此有什么想法吗?
【问题讨论】:
-
Babel 对
=>函数所做的与.bind()所做的有何不同? -
使用粗箭头函数将其保存在闭包中
-
是的。你认为
.bind()做了什么? -
我正在查看转译后的代码,它看起来完全一样,但我不确定它在做什么
-
重点是,必须将
this的上下文值保存在某处。在.bind()成为语言的一部分之前,它通常是通过闭包实现的,没有理由怀疑它现在基本上不一样了(尽管增加了一些行为)。
标签: javascript reactjs ecmascript-6 arrow-functions class-fields