# This

This page talks about the keyword this within the context of handling Events.

The keyword this can be a confusing one in JavaScript. It is typically a reference to the object that made a function run.

For the purposes of this discussion we will limit the use of this to functions triggered by event listeners.

let btn1 = document.getElementById('myButton');
let btn2 = document.querySelector('.btn');
let btn3 = document.querySelector('#otherButton');

btn1.addEventListener('click', makeNoisy);
btn2.addEventListener('click', makeNoisy);
btn3.addEventListener('click', makeNoisy);

function makeNoisy(ev) {
  ev.currentTarget.style.backgroundImage = 'url(./img/noisy-pattern.png)';
}
1
2
3
4
5
6
7
8
9
10
11

In this example we have three different buttons being referenced in the variables btn1, btn2, and btn3.

All three buttons have a click listener.

All three click listeners will call the function makeNoisy( ).

Inside the function makeNoisy, we are able to tell which button needs to have the background image added because ev.target gives us that information. The target property points to the button that was clicked.

The keyword this works in the same way.

function makeNoisy(ev) {
  this.style.backgroundImage = 'url(.img/noisy-pattern.png)';
}
1
2
3

We can replace ev.target with this.

This points to the object written in front of addEventListener( ).

To learn a lot more about the keyword this watch the following video:

# Beyond Events

This excerpt from the You Don't Know JS book by Kyle Simpson gives a good description of the 4 rules for determining the value of this. Here is the link to the page in You Don't Know JS


We can summarize the rules for determining this from a function call's call-site,in their order of precedence. Ask these questions in this order, and stop when the first rule applies.

  1. Is the function called with new (new binding)? If so, this is the newly constructed object.
var bar = new foo();
1
  1. Is the function called with call or apply (explicit binding), even hidden inside a bind hard binding? If so, this is the explicitly specified object.
var bar = foo.call(obj2);
1
  1. Is the function called with a context (implicit binding), otherwise known as an owning or containing object? If so, this is that context object.
var bar = obj1.foo();
1
  1. Otherwise, default the this (default binding). If in strict mode, pick undefined, otherwise pick the global object.
var bar = foo();
1

That's it. That's all it takes to understand the rules of this binding for normal function calls. Well... almost.


There are a few exceptions.

Arrow functions are one of those exceptions. Read more about Arrow functions and this

Back to Week main page

Last Updated: 11/1/2020, 2:32:17 PM