Javascript class methods versus properties

后端 未结 2 1663
借酒劲吻你
借酒劲吻你 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.

提交回复
热议问题