This parameter outside of expected inside an anonymous function

Asked

Viewed 36 times

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?

1 answer

4


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

There are many ways to escape from this, you could use bind, call, apply, that. But because the question has the ES6 tag, I recommend using a Arrow Function, because she keeps the this where she was raised.

See 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);

  • I just didn’t understand the functionality of the variable name in the code.

  • 1

    I copied from the question, also did not understand kk. Anyway I preferred to leave...

  • KKKK... blza Francisco.

  • @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.

  • @Francisco, all anonymous functions have this behavior?

  • 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 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?

  • 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.

  • I found this one on Medium https://blog.bitsrc.io/understanding-execution-context-and-execution-stack-in-javascript-1c9ea8642dd0

Show 4 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.