I made a code to train Arrays and JavaScript manipulation. Here's 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 executes the function within forEach
is the global object. Without this
, the scope is that of the object created by Playlist()
. Can anyone explain to me why this occurs?