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?
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
thisandargumentsare 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 ofthisfrom the context in which they are defined. This means that this in an arrow function refers to thethissurrounding the function, and it is not possible to change itsthisusingbind,call, orapply. They do not have their own argumentsobject. 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
objectwhich contains the arguments passed to the function.Difference between arrow and regular functions