Hello, my name is: Amy

Explain how `this` works in JavaScript

My understanding of this was greatly helped by reading (and re-reading) Kyle Simpsons explanation in his book You don't Know JS.

The general idea of this is that it is a reference to an object that is determend by where the function is called. This assoction happens at runtime when the function is invoked, rather than when it is written.

The first step in determining what that object is is to see exactly where the function is called. One (super helpul) way to do that is by using the debugger in development tools. Using Kyle's example code, you can use console tools to use determine exactly where this function is called.

Example of using developer tools in chrome to debug and find the call stack.

There are ways, such as using .call(), .apply(), and .bind(), to specify which object reference the function should have.

Example using .call()

.call(valueOfThis[, arg1[, arg2[, ...]]])

The call() method calls a function with a given this value and arguments provided individually.

Example of .call():

function appleCost() {
  return this.apples * 0.5;
}
function howManyApples() {
  return this.name + ' has ' + this.apples + ' apples worth $' + appleCost.call(this);
}
var amy = { 
  name: 'amy',
  apples: 10
}
var matt = {
  name: 'matt',
  apples: 5
}
howManyApples.call(matt);  // matt has 5 apples worth $2.5
howManyApples.call(amy);   // amy has 10 apples worth $5

I still get a little tripped up as to what this really is, especially when using callback functions in event listeners. In order to get my desired effect I will often assign the value of this to a variable, _this = this;. The next time that comes up I should try using .bind() and actually use this as intended.

Comments