Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
299 views
in Technique[技术] by (71.8m points)

javascript - Can I use arrow function in constructor of a react component?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...