With Vue 3 composition API and script setup, I've seen two ways for defining methods within a component:
using arrow functions const increment = () => {}
Using the regular function syntax function increment()
Which way is correct?
The two ways are ok, the major difference is how this
and arguments
are handled, and how they behave as a constructor. Syntax and clarity also play a role in choosing between the two. But apart from that, you can use the two of them as you want to. There is no better ways of doing it.
Arrow functions do not have their own this
. They capture the value of this
from the context in which they are defined. This means that this in an arrow function refers to the this
surrounding the function, and it is not possible to change its this
using bind
, call
, or apply
. They do not have their own arguments object
. You will need to use the rest of the parameters (...args) to access the arguments.
Regular functions have their own this, which is determined by how they are called.
They have their own arguments object
which contains the arguments passed to the function.