Today, while working with Vue, I came across an interesting observation.
When initially using Vue, there were two common ways to define a method:
methods: {
foo: () => {
//perform some action
}
}
and
methods: {
foo() {
//perform some action
}
}
Both of these methods worked perfectly fine. However, today, when I tried defining a method similar to the first example, I encountered some issues with the scope of this
inside the function.
Just to provide some context:
I had my data defined as follows:
data() {
return {
fooVar: ''
}
}
The method I defined looked like this:
methods: {
foo: () => {
console.log('Foo: ' + this.fooVar);
}
}
Upon checking the console, it displayed:
Foo: undefined
Subsequently, I modified the method declaration to:
foo() {
console.log('Foo: ' + this.fooVar)
}
Surprisingly, this change resolved the issue without any hassle.
Although I believed that foo() {...}
and foo: () => {...}
are essentially equivalent (excluding syntax differences), I began to wonder if the scope of the function differs between the two approaches.
Does the scope indeed change, and if so, what prompts this change?