Hemanth's Scribes

javascript

Selfless JavaScript

Author Photo

Hemanth HM

Thumbnail

Don’t be misled by the title - I’m talking about avoiding explicitly saving context with self = this.

What is this bound to?

  • In .call()/.apply(): first argument
  • In .bind(): first argument passed during function creation
  • In object.method(): the object
  • Otherwise: global context

The Problem

var names = ["hemanth", "gnumanth", "yomanth"];

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

greet.greetThem(names);
// undefined hemanth, undefined gnumanth, undefined yomanth

## Common Workaround: Save Context
javascript
greetThem: function(names) {
  var self = this;
  names.forEach(function(name) {
    console.log(self.msg + " " + name);
  })
}

## Better Approach: Use bind()
javascript
greetThem: function(names) {
  names.forEach(function(name) {
    console.log(this.msg + " " + name);
  }.bind(this));
}
// Yo! hemanth, Yo! gnumanth, Yo! yomanth

This is especially useful when there are n levels of nesting where you’d need that = this, self = this, etc. Just bind() as needed!

#javascript
Author Photo

About Hemanth HM

Hemanth HM is a Sr. Machine Learning Manager at PayPal, Google Developer Expert, TC39 delegate, FOSS advocate, and community leader with a passion for programming, AI, and open-source contributions.