Why this?

If the this mechanism is so confusing, even to seasoned JavaScript developers, one may wonder why it’s even useful? Is it more trouble than it’s worth? Before we jump into the how, we should examine the why.

Let’s try to illustrate the motivation and utility of this:

  1. function identify() {
  2. return this.name.toUpperCase();
  3. }
  4. function speak() {
  5. var greeting = "Hello, I'm " + identify.call( this );
  6. console.log( greeting );
  7. }
  8. var me = {
  9. name: "Kyle"
  10. };
  11. var you = {
  12. name: "Reader"
  13. };
  14. identify.call( me ); // KYLE
  15. identify.call( you ); // READER
  16. speak.call( me ); // Hello, I'm KYLE
  17. speak.call( you ); // Hello, I'm READER

If the how of this snippet confuses you, don’t worry! We’ll get to that shortly. Just set those questions aside briefly so we can look into the why more clearly.

This code snippet allows the identify() and speak() functions to be re-used against multiple context (me and you) objects, rather than needing a separate version of the function for each object.

Instead of relying on this, you could have explicitly passed in a context object to both identify() and speak().

  1. function identify(context) {
  2. return context.name.toUpperCase();
  3. }
  4. function speak(context) {
  5. var greeting = "Hello, I'm " + identify( context );
  6. console.log( greeting );
  7. }
  8. identify( you ); // READER
  9. speak( me ); // Hello, I'm KYLE

However, the this mechanism provides a more elegant way of implicitly “passing along” an object reference, leading to cleaner API design and easier re-use.

The more complex your usage pattern is, the more clearly you’ll see that passing context around as an explicit parameter is often messier than passing around a this context. When we explore objects and prototypes, you will see the helpfulness of a collection of functions being able to automatically reference the proper context object.