3
I made a code to train handling Arrays and Javascript. This is part of the code:
function Playlist (nome ='Playlist'){
const musicas = [];
function addMusicas(...novasMusicas){
novasMusicas.forEach(function(musica){
// aqui o this é o objeto global
this.musicas.unshift(musica);
})
}
return {
nome,
musicas,
addMusicas,
}
}
const playlist01 = new Playlist();
playlist01.addMusicas('Dream on', 'Drive', 'Sex and Candy');
Note that whoever performs the function within the forEach
is the global object. Without the this
, the scope is that of the object created by Playlist()
. Can someone explain to me why this occurs?
I just didn’t understand the functionality of the variable name in the code.
– LeAndrade
I copied from the question, also did not understand kk. Anyway I preferred to leave...
– Francisco
KKKK... blza Francisco.
– LeAndrade
@Leandrade, I just copied part of the code and forgot to delete what I wasn’t using. The real focus is on the rsrs question.
– Icaro Rego Fernandes
@Francisco, all anonymous functions have this behavior?
– Icaro Rego Fernandes
Dude, the fact is not to be an anonymous function, it doesn’t change this. The
this
changes depending on how the function is called.– Francisco
@Francisco But in this case, how can the global object access the function that is inside the foreach, if it is running inside the addMusicas function? Have some method to understand more clearly the context of Javascript execution?
– Icaro Rego Fernandes
The global object does not access the function, the function accesses the global object. On recommendation, I do not have, but just give a googlada you find many legal articles and documents.
– Francisco
I found this one on Medium https://blog.bitsrc.io/understanding-execution-context-and-execution-stack-in-javascript-1c9ea8642dd0
– Icaro Rego Fernandes