问题描述
这个问题类似于当使用 React 时,最好在构造函数中使用粗箭头函数还是绑定函数? 但有点不同.您可以在构造函数中将函数绑定到 this
,或者在构造函数中仅应用箭头函数.请注意,我只能在我的项目中使用 ES6 语法.
This question is similar to When using React Is it preferable to use fat arrow functions or bind functions in constructor? but a little bit different. You can bind a function to this
in the constructor, or just apply arrow function in constructor. Note that I can only use ES6 syntax in my project.
1.
class Test extends React.Component{
constructor(props) {
super(props);
this.doSomeThing = this.doSomeThing.bind(this);
}
doSomething() {}
}
2.
class Test extends React.Component{
constructor(props) {
super(props);
this.doSomeThing = () => {};
}
}
这两种方式的优缺点是什么?谢谢.
What's the pros and cons of these two ways? Thanks.
推荐答案
出于某些原因,选项 1 通常更可取.
Option 1 is generally more preferable for certain reasons.
class Test extends React.Component{
constructor(props) {
super(props);
this.doSomeThing = this.doSomeThing.bind(this);
}
doSomething() {}
}
原型方法更易于扩展.子类可以用
Prototype method is cleaner to extend. Child class can override or extend doSomething
with
doSomething() {
super.doSomething();
...
}
当实例属性
this.doSomeThing = () => {};
或 ES.next 类字段
or ES.next class field
doSomeThing = () => {}
代替,调用 super.doSomething()
是不可能的,因为该方法没有在原型上定义.覆盖它会导致在父和子构造函数中两次分配 this.doSomeThing
属性.
are used instead, calling super.doSomething()
is not possible, because the method wasn't defined on the prototype. Overriding it will result in assigning this.doSomeThing
property twice, in parent and child constructors.
混合技术也可以使用原型方法:
Prototype methods are also reachable for mixin techniques:
class Foo extends Bar {...}
Foo.prototype.doSomething = Test.prototype.doSomething;
原型方法更易于测试.它们可以在类实例化之前被监视、存根或模拟:
Prototype methods are more testable. They can be spied, stubbed or mocked prior to class instantiation:
spyOn(Foo.prototype, 'doSomething').and.callThrough();
这可以在某些情况下避免竞争条件.
This allows to avoid race conditions in some cases.
这篇关于我可以在 React 组件的构造函数中使用箭头函数吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!