Understanding the magic of “this” keyword in JavaScript

Image credit

Introduction

Why this?

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

function speakName() {
var greeting = "Hello, I'm " + identifyName.call( this );
console.log( greeting );
}
var me = {
name: "Sam"
};

var you = {
name: "David"
};

identifyName.call( me ); // SAM
identifyName.call( you ); // DAVID

speakName.call( me ); // Hello, I'm SAM
speakName.call( you ); // Hello, I'm DAVID
function identifyName(context) {
return context.name.toUpperCase();
}

function speakName(context) {
var greeting = "Hello, I'm " + identifyName( context );
console.log( greeting );
}

identifyName( you ); // DAVID
speakName( me ); // Hello, I'm SAM

Clearing Confusions and Misconceptions about this

Itself

function counter(num) {
console.log( "counter: " + num );
// keep track of how many times `counter` is called
this.count++;
}

counter.count = 0;

var i;

for (i=0; i<10; i++) {
if (i > 5) {
counter( i );
}
}
// counter: 6
// counter: 7
// counter: 8
// counter: 9

// how many times was `counter` called?
console.log( counter.count ); // 0 -- WTH! How did this happen?
function counter(num) {
console.log( "counter: " + num );

// keep track of how many times `counter` is called
data.count++;
}

var data = {
count: 0
};

var i;

for (i=0; i<10; i++) {
if (i > 5) {
foo( i );
}
}
// counter: 6
// counter: 7
// counter: 8
// counter: 9

// how many times was `counter` called?
console.log( data.count ); // 4

Its Scope

function foo() {
var a = 2;
this.bar();
}

function bar() {
console.log( this.a );
}

foo(); //undefined
Image Credit
var myVar = 100;

function WhoIsThis() {
var myVar = 200;

console.log("myVar = " + myVar); // 200
console.log("this.myVar = " + this.myVar); // 100
}
WhoIsThis(); // inferred as window.WhoIsThis()

Things To Keep In Mind:

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store