Following a Vue tutorial , in which fetch
an API that returns an image of cats is made, I suddenly came to a curious situation.
new Vue({
el: '#app',
data: {
catSrc: null,
},
...
this.catSrc = null;
let res = fetch("https://api.thecatapi.com/v1/images/search",{
method: "GET",
headers: {
"x-api-key": API_KEY,
"Accept":"application/json",
},
})
.then(function(response) {
return response.json();
})
.then(function(data){
return data[0].url;
});
let getImg = () => {
res.then((result) => {
this.catSrc = result;
});
};
getImg();
The above does and I manage to return the value of the promise to the Vuefetch
dynamic variable , but since I first thought of "converting" the arrow function, the alternative never returned the value that the arrow function does return.
Can someone explain to me why of this?
The "normal" function I tried to use was:
let getImg = function () {
res.then(function (result) {
this.catSrc = result;
});
};
getImg();
It's because of how the context of this changes in a normal function and in an arrow function. The execution context changes a lot.
The property this.catSrc belongs to the context of the vue object, when new functions are declared with function() that are not properties of an object these functions have their own context. So within them, this no longer belongs to the vue object, but instead belongs to the function() context, which can be the default window object or undefined in js strict mode.
Arrow functions do not declare new contexts and therefore any this within them refers to the parent context, in this case the vue object which is the one with the property of interest.