this is a keyword that essentially lets us process several different types of elements with one universal section of code. In JavaScript, the this keyword refers to an object.
The this keyword refers to different objects depending on how it is used:
In an object method, this refers to the object.
Alone, this refers to the global object.
In a function, this refers to the global object.
In a function, in strict mode, this is undefined.
In an event, this refers to the element that received the event.
Methods like call(), apply(), and bind() can refer this to any object.
*Note: this is NOT a variable. It is a keyword. You cannot change the value of this.
The this keyword refers to the context where a piece of code, such as a function's body, is supposed to run. Most typically, it is used in object methods, where this refers to the object that the method is attached to, thus allowing the same method to be reused on different objects.
Arrow functions differ in their handling of this: they inherit this from the parent scope at the time they are defined. This behavior makes arrow functions particularly useful for callbacks and preserving context. However, arrow functions do not have their own this binding. Therefore, their this value cannot be set by call(), apply() or bind() methods, nor does it point to the current object in object methods.
In the example at the bottom of this page, we have a section set up with several boxes. These boxes are just simple HTML buttons with some CSS styling,
<button>CLICK</button>
We want be able to click on any button and have it change both the foreground and background colors of that individual button. For this we need some JavaScript.
1). First we need to define a function to create the random foreground and background colors:
const makeRandColor = () => {
// picks random r/g/b colors and assigns them to fc (foreground color)
let r = Math.floor(Math.random() * 255);
let g = Math.floor(Math.random() * 255);
let b = Math.floor(Math.random() * 255);
const fc = `rgb(${r}, ${g}, ${b})`;
// picks random r/g/b colors and assigns them to bc (background color)
let r = Math.floor(Math.random() * 255);
let g = Math.floor(Math.random() * 255);
let b = Math.floor(Math.random() * 255);
const bc = `rgb(${r}, ${g}, ${b})`;
// we run the color randomization twice to get two different random colors, one for foreground and the other for background
so buttons becomes an object that represents all of the buttons.
3). Next we need to create a for loop, so that we can process each individual button, within the buttons object, with a click event and a callback function.
for (let button of buttons) {
button.addEventListener('click', colorize)
// adds a click event to each button of the object buttons
// when clicked, it runs the callback functioncolorize
}
4). And finally, we need to define the callbackFunctioncolorize
function colorize() {
const [fc, bc] = makeRandColor();
// returns random fc and bc colors
this.style.color = fc;
// assigns the foreground color
this.style.backgroundColor = bc;
// assigns the background color
}
So colorize() will run the imbedded function makeRandColor() which will create the random foreground (fc) and background (bc) colors, and assign them to this button object.
Instead of applying these colors to the variable button, we are applying them to the keyword this. Because, in this instance, this was assigned within the parent Objectbuttons, so this refers to each individual item (button) of the buttons object.
So instead of saying
button.style.backgroundColor = bc;
we are saying
this.style.backgroundColor = bc;
because this is referring to the individual button of the parent object buttons.
a) creating a buttons object that represents all of the buttons
b) looping thru the buttons object to process each button individually
c) running the callback functioncolorize on each individual button of the buttons object, when it is clicked
And if we look at the callback functioncolorize:
function colorize() {
const [fc, bc] = makeRandColor();
this.style.color = fc;
this.style.backgroundColor = bc;
}
Because this was called by the object button, it is referring to the individual button.
Now we can really discuss the usefulness of this.
If we we are only dealing with one element type such as our buttons, we could have just used a variable in our callback function, and assigned the random color to that:
button.style.foregroundColor = fc;
button.style.backgroundColor = bc;
But what if we are dealing with more than one element type?
After our row of buttons below, is another row of span elements,
<span>Click Me Too</span>
and now we want to apply the same changing color effect as we did with the buttons, to the <span> elements. This scenario shows us a prime example, of why we want to use the this keyword.
If we didn't utilize the this keyword, we would have to duplicate the entire section of the callback functioncolorize, for the click event(step 4 from above) using variables instead of this.
span.style.foregroundColor = fc;
span.style.backgroundColor = bc;
But since we are using the keyword this in our callback function, all we have to do is define a new object for the span elements.
const spans = document.querySelectorAll('span');
for (let span of spans) {
span.addEventListener('click', colorize)
}
and now that we have created the span object, AND because we are using this in our callback functioncolorize:
this.style.foregroundColor = fc;
this.style.backgroundColor = bc;
this is now referring to the individual span object, just lik it did with the individual button object. So we get exactly the same changing color effect with the <span> elements, as we got with the <button> elements, without having to completely rewrite and duplicate the callback functioncolorize.
And Therein lies the beauty of using this. We can process multiple object types with the same function, using the this keyword.
This was a very simple example with only two objects, and a very simple callback function. But at times our functions can be much longer and more complicated, so if we can only use one function to process multiple objects, it greatly simplifies our coding.
Change the Box Colors
(using RGB colors)
Click a Box to change the colors
Click Me TooClick Me TooClick Me TooClick Me TooClick Me TooClick Me TooClick Me Too