问题
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