Can I use arrow function in constructor of a react component?
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(); ...}
When instance property
this.doSomeThing = () => {};
or ES.next class field
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.
I think you may want like this. It is the same with your first situation.it will work in stage-2 with babel. (transform-class-properties : http://babeljs.io/docs/plugins/transform-class-properties/)(preset-stage-2: http://babeljs.io/docs/plugins/preset-stage-2/)
class Test extends React.Component{ constructor(props) { super(props); } doSomeThing = () => {}}
Approach 1 is more readable for me and more idiomatic.
Besides, declaring methods inside a class instead of constructor, the methods can be shared.
class Foo { test() {}}const f1 = new Foo()const f2 = new Foo()f1.test === f2.test // true
In approach 2, you will declare all the methods every time you create a new instance:
class Foo { constructor() { this.test = () => {} }}const f1 = new Foo()const f2 = new Foo()// the method is not shareablef1.test === f2.test // false
Theoretically the approach 2 is slower, but the impact on performance should be negligible.
I'll simply go for approach 1, since it's used in the React documentation, also I never saw anyone use approach 2.
I just ran some samples to test the performance. In latest Chrome (Mac), declaring methods in constructor is about 90% slower than using bind
in constructor.