Skip to content

Instantly share code, notes, and snippets.

@theankitgaurav
Created November 20, 2016 07:35
Show Gist options
  • Save theankitgaurav/2e21f602335e5fab3d8b57428d6345b1 to your computer and use it in GitHub Desktop.
Save theankitgaurav/2e21f602335e5fab3d8b57428d6345b1 to your computer and use it in GitHub Desktop.
An elegant illustration of the utility of 'this' in javascript

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:

function identify() {
    return this.name.toUpperCase();
}

function speak() {
    var greeting = "Hello, I'm " + identify.call( this );
    console.log( greeting );
}

var me = {
    name: "Kyle"
};

var you = {
    name: "Reader"
};

identify.call( me ); // KYLE
identify.call( you ); // READER

speak.call( me ); // Hello, I'm KYLE
speak.call( you ); // Hello, I'm READER
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment