This outside-expected parameter within an anonymous function

3

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?

    
asked by anonymous 15.12.2018 / 16:00

1 answer

4

This occurs because when a function is not a property of an object, it is invoked with the this parameter attached to the global object.

There are several ways to escape this, you could use bind , call , apply , that . But because the question has the ES6 tag, I recommend that you use a arrow , because it retains this from where it was created.

Here's how it would look:

function Playlist (nome ='Playlist'){
    const musicas = [];
    function addMusicas(...novasMusicas){
        novasMusicas.forEach(musica => { // perceba aqui a sintaxe da criação de uma arrow function
            this.musicas.unshift(musica);
        })
    }
    return {
        nome,
        musicas,
        addMusicas,
    }
}

const playlist01 = new Playlist(); 
playlist01.addMusicas('Dream on', 'Drive', 'Sex and Candy');
console.log(playlist01.musicas);
    
15.12.2018 / 18:09