Hemanth.HM

A Computer Polyglot, CLI + WEB ♥'r.

Selfless Javascript

| Comments

Don't get mislead by the title, all I'm trying to do is avoding explicity saving of the context with something like self=this.

What would 'this' be bound to?

  • this will be set to the first argument passed in case of .call()/.apply().

  • In case of .bind(), this will be the first argument that was passed to .bind() during the function was creation.

  • On object.method(), this will refer to that object.

  • Rest, this will reffer to the global context.

Let's see a simple usecase :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
var names = ["hemanth","gnumanth","yomanth"];

greet = {
    msg: "Yo! ",
    greetThem: function (names) {
        names.forEach(function (name) {
            console.log(this.msg + " " + name);
        })
    }
}

greet.greetThem(names);

// Would log :
/*
undefined hemanth
undefined gnumanth
undefined yomanth
*/

The work around is pretty simple and famous : save the context!

1
2
3
4
5
6
7
8
9
10
11
12
13
var names = ["hemanth","gnumanth","yomanth"];

greet = {
    msg: "Yo! ",
    greetThem: function (names) {
        var self = this;
        names.forEach(function (name) {
            console.log(self.msg + " " + name);
        })
    }
}

greet.greetThem(names);

But, even more better approach would be to avoid self=this altogehter and take the advantage of bind()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
var names = ["hemanth","gnumanth","yomanth"];

greet = {
    msg: "Yo! ",
    greetThem: function (names) {
        names.forEach(function (name) {
            console.log(this.msg + " " + name);
        }.bind(this));
    }
}

greet.greetThem(names);

// Both of them would log :
Yo!  hemanth
Yo!  gnumanth
Yo!  yomanth

This was just a simple use case to make things clear, but this kind of paradigm would be really useful when there are n levels of nesting. Where one has to save context as that = this, self = this and so on... instead bind() them as per the need!

Comments