GodziLaravel's avatar

why using : let self = this?

Hello,

I would like to know why in Vue js it's recommended to use let self = this; instead of "this." ?

thanks

0 likes
6 replies
jlrdw's avatar

Assigning the current context of this to get something else.

Say this was currently 5

You want to get 5 squared, but leave the original 5 alone.

So square self, not this.

It's not a vue thing, it's JS.

tykus's avatar

Where is this recommended?

The usual reason for assigning self is to keep a reference to this in another scope which defines its own this, e.g. inner functions (other variables in the containing scope will be available, hence assigning the outer this to self

function () {
    // `this` is scoped to the outer function scope

    let self = this;
    
    function () {
        // `this` is scoped to the inner function
        // `self` is `this` from the outer scope
    }
}
5 likes
steve_laracasts's avatar

It is used in Spark which I am taking to be a source of truth, and yeah, it is because of the availability / scope of this within nested functions, eg:

    created() {
        this.getProjects();
        var self = this;
        Bus.$on('projectCreated', function(project) {
            self.projects.push(project);
        });
        Bus.$on('updateProjects', function () {
            self.getProjects();
        });
    },

This doesn't work without the var self = this; line.

1 like
artcore's avatar

In arrow functions this is the surrounding context. No need to store it as self first.

thing.addEeventListener('click', e=>
    {
        console.log(this);
    });

thing.addEeventListener('click', function(e)
    {
        console.log(this);
    });
1 like
artcore's avatar

Yeh, it's a real improvement. Using it every day since I learned it ;)

Cheers

Please or to participate in this conversation.