Javascript class methods versus properties

后端 未结 2 1662
借酒劲吻你
借酒劲吻你 2021-02-06 01:32

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

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

  hand         


        
相关标签:
2条回答
  • 2021-02-06 01:47

    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.

    0 讨论(0)
  • 2021-02-06 01:51

    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.

    0 讨论(0)
提交回复
热议问题