---
title: "Selfless JavaScript"
description: "Avoiding self=this by using bind() for context preservation. Practical notes and code examples on Selfless JavaScript by."
url: "https://h3manth.com/scribe/selfless-javascript/"
canonical_url: "https://h3manth.com/scribe/selfless-javascript/"
markdown_url: "https://h3manth.com/scribe/blog/selfless-javascript.md"
publishDate: "2013-05-26T00:00:00.000Z"
author: "Hemanth HM"
category: "javascript"
tags: ["javascript"]
word_count: 160
reading_time_minutes: 1
x_markdown_tokens: 372
content_signal: "ai-train=yes, search=yes, ai-input=yes"
---

# Selfless JavaScript

> Avoiding self=this by using bind() for context preservation. Practical notes and code examples on Selfless JavaScript by.

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

```javascript
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!
