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!
Ans: A property is a named attribute of an object. Properties define the characteristics of an object such as Size, Color etc. or sometimes the way in which it behaves. A method is an action that can be performed on objects.
In most cases, methods are actions and properties are qualities. Using a method causes something to happen to an object, while using a property returns information about the object or causes a quality about the object to change.
JavaScript is designed on a simple object-based paradigm. An object is a collection of properties, and a property is an association between a name (or key) and a value. A property's value can be a function, in which case the property is known as a method.
a class describes the contents of the objects that belong to it: it describes an aggregate of data fields (called instance variables), and defines the operations (called methods).
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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With