Javascript class methods versus properties

点点圈 提交于 2020-01-31 03:39:26

问题


I've seen code using Javascript classes use the following form (example is React):

class UserProfile extends Component {
  state = {
    open: false
  }

  handleOpen = () => {
    this.setState({ open: true })
  }
}

Why is handleOpen implemented as a property which is set to a function instead of something like:

class UserProfile extends Component {
  state = {
    open: false
  }

  handleOpen() {
    this.setState({ open: true })
  }
}

Thanks in advance!


回答1:


That's also a function, but it's called an arrow function and works slightly differently from the "traditional" implementation. It was introduced with ECMAScript 6.

Here's what the MDN docs says:

An arrow function expression has a shorter syntax than a function expression and does not bind its own this, arguments, super, or new.target. These function expressions are best suited for non-method functions, and they cannot be used as constructors.


One of the major benefits is that you wouldn't need to bind this to that function, because arrow functions do not have their own this object:

Until arrow functions, every new function defined its own this value

This guarantees scope safety; it's impossible to use the incorrect this by accident. It is arguably also slightly more readable.

A drawback however would be that arrow functions are anonymous, meaning that it would be harder to do a stack trace when you get an error in your code.But for React applications we can use devtool:'cheap-module-eval-source-map' from babel to easily find bugs in our stack trace.




回答2:


It's about the context of this inside of your method. If you would implement it like your second example, this won't reference the component instance, using the arrow function like in your first example this references the component instance. (Due to not using React.createClass).

For your second example you have to do this.handleOpen = this.handleOpen.bind(this) inside your constructor.

EDIT: For details about arrow functions see the answer from Chris.



来源:https://stackoverflow.com/questions/44423947/javascript-class-methods-versus-properties

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!