Simple JavaScript Misconceptions— the ‘this’ keyword (Part 1)

Functions are ubiquitous when working with JavaScript. Upon creation, every JavaScript function contains within its scope an automatically defined special keyword called “this”. The “this” keyword is often misused and misunderstood and in this blurb, I will point out one of the most common misconceptions surrounding “this”.


“this” is not supposed to happen…

  1. The “this” keyword refers to the function itself.

It is a common mistake when working with JavaScript to infer that “this” refers to the function itself. We will see by working through the code example below why this is not an accurate assumption.

function foo(num) {
console.log( "foo: " + num );

// keep track of how many times `foo` is called
this.count++;
}

foo.count = 0;

let i;

for (i=0; i<5; i++) {
if (i > 0) {
foo( i );
}
}
// foo: 1
// foo: 2
// foo: 3
// foo: 4

// how many times was `foo` called?
console.log( foo.count ); // 0 ??
//CODE COURTESY OF KYLE SIMPSON https://github.com/getify

We see that our code runs and four “console.log” statements are visible. So why is our count property still 0? This is due to the fact that a “count” property is being added to our “foo” function object but the “this.count” reference inside the “foo” function is not pointing to our function but rather at a different root object.

Like what you read? Give Hai Zhu a round of applause.

From a quick cheer to a standing ovation, clap to show how much you enjoyed this story.