Learn about the “this” keyword in JavaScript and how it behaves in different contexts. Explore examples, usage scenarios, and best practices for effectively utilizing “this” in your code.
Concepts : “this” keyword in JavaScript, function context in JavaScript, global scope in JavaScript, object method binding, constructor functions in JavaScript, event handlers and “this” in JavaScript, explicit function binding in JavaScript, strict mode and “this” keyword
Here are some common ways this is used:
Global scope: When this is used outside of any function or object, it refers to the global object. In a web browser, the global object is the window object.
Function context: When a function is called as a method of an object, this refers to the object that the function is a property of. For example:
function Person(name) { this.name = name; } const person1 = new Person("Omar"); console.log(person1.name); // Output: Omar
In this example, this inside the sayHello function refers to the obj object because sayHello is called as a method of obj.
Constructor functions: When a function is used as a constructor with the new keyword, this refers to the newly created object. Constructor functions are used to create multiple objects with similar properties and methods.
For example:
In this case, this inside the Person function refers to the newly created object (person1), and the name property is assigned to that object.
Event handlers: When a function is used as an event handler, this refers to the element that triggered the event. For example:
const button = document.querySelector("button"); button.addEventListener("click", function() { console.log(this); // Output: <button>...</button> });
In this case, this inside the event handler function refers to the button element that was clicked.
Note that the value of this can be explicitly set using methods like call(), apply(), or bind(), which allow you to control the context in which a function is executed.
It’s important to understand the context in which this is used because it can vary depending on how a function is called, and using this incorrectly can lead to unexpected behavior or errors in your code.
Here’s an example of JavaScript code in an HTML file that demonstrates the global scope:
<!DOCTYPE html> <html> <head> <title>Global Scope Example</title> </head> <body> <script> // JavaScript code in the global scope alert(this); // Output: [object Window] function sayHello() { document.write("Hello, global scope!"); document.write(this); // Output: [object Window] } sayHello(); </script> </body> </html>
Explanation:
Here’s an example of JavaScript code in an HTML file that demonstrates the function context
<!DOCTYPE html> <html> <head> <title>Function Context Example</title> </head> <body> <script> const obj = { name: "Omar", sayHello: function() { document.write("Hello, " + this.name); document.write(this); // Output: {name: "Omar", sayHello: ƒ} } }; obj.sayHello(); </script> </body> </html>
Explanation:
Here’s an example of JavaScript code in an HTML file that demonstrates the use of constructor functions:
<!DOCTYPE html> <html> <head> <title>Constructor Function Example</title> </head> <body> <script> function Person(name) { this.name = name; } const person1 = new Person("Omar"); console.log(person1.name); // Output: Omar </script> </body> </html>
Explanation:
Here’s an example of JavaScript code in an HTML file that demonstrates the use of event handlers:
<!DOCTYPE html> <html> <head> <title>Event Handler Example</title> </head> <body> <button id="myButton">Click Me!</button> <script> const button = document.getElementById("myButton"); button.addEventListener("click", function() { console.log("Button clicked!"); console.log(this); // Output: <button id="myButton">Click Me!</button> }); </script> </body> </html>
Explanation:
Here’s an example of JavaScript code in an HTML file that demonstrates the use of this within a method:
<!DOCTYPE html> <html> <head> <title>Event Handler Example</title> </head> <body> <button id="myButton">Click Me!</button> <script> const button = document.getElementById("myButton"); button.addEventListener("click", function() { console.log("Button clicked!"); console.log(this); // Output: <button id="myButton">Click Me!</button> }); </script> </body> </html>
Explanation:
Here’s an example of JavaScript code in an HTML file that demonstrates the use of this within a method:
<!DOCTYPE html> <html> <head> <title>this in a Method Example</title> </head> <body> <script> const obj = { name: "Omar", sayHello: function() { console.log("Hello, " + this.name); console.log(this); // Output: {name: "Omar", sayHello: ƒ} } }; obj.sayHello(); </script> </body> </html>
Explanation:
Here’s an example of JavaScript code in an HTML file that demonstrates the use of this in isolation:
<!DOCTYPE html> <!DOCTYPE html> <html> <head> <title>this Alone Example</title> </head> <body> <script> document.write(this); // Output: [object Window] </script> </body> </html>
Explanation:
Here’s an example of JavaScript code in an HTML file that demonstrates the use of this in a function without any explicit binding:
Explanation:
Here’s an example of JavaScript code in an HTML file that demonstrates the use of this in a function without any explicit binding:
<!DOCTYPE html> <html> <head> <title>this in a Function Example</title> </head> <body> <script> function greet() { document.write("Hello, " + this); // Output: Hello, [object Window] } greet(); </script> </body> </html>
Explanation:
Here’s an example of JavaScript code in an HTML file that demonstrates the use of this in a function with strict mode enabled:
<!DOCTYPE html> <html> <head> <title>this in a Function (Strict) Example</title> </head> <body> <script> "use strict"; function greet() { document.write("Hello, " + this); // Output: Hello, undefined } greet(); </script> </body> </html>
Explanation:
Here’s an example of JavaScript code in an HTML file that demonstrates the use of this in an event handler:
<html> <head> <title>this in Event Handlers Example</title> </head> <body> <button id="myButton">Click Me!</button> <script> function handleClick() { document.write("Button clicked!"); document.write(this); // Output: <button id="myButton">Click Me!</button> } const button = document.getElementById("myButton"); button.addEventListener("click", handleClick); </script> </body> </html>
Explanation:
Here’s an example of JavaScript code in an HTML file that demonstrates object method binding:
<!DOCTYPE html> <html> <head> <title>Object Method Binding Example</title> </head> <body> <script> const obj = { name: "Omar", sayHello: function() { document.write("Hello, " + this.name); } }; const obj2 = { name: "Omar" }; const greet = obj.sayHello.bind(obj2); greet(); // Output: Hello, Omar </script> </body> </html>
Explanation:
Here’s an example of JavaScript code in an HTML file that demonstrates explicit function binding using call() and apply():
<!DOCTYPE html> <html> <head> <title>Explicit Function Binding Example</title> </head> <body> <script> function sayHello() { document.write("Hello, " + this.name); } const obj = { name: "Omar" }; const obj2 = { name: "Omar" }; sayHello.call(obj); // Output: Hello, Omar sayHello.call(obj2); // Output: Hello, Omar sayHello.apply(obj); // Output: Hello, Omar sayHello.apply(obj2); // Output: Hello, Omar </script> </body> </html>
Explanation:
One possible application of the concept of the this keyword in JavaScript is in the development of an interactive web page with interactions.
Let’s consider an example where you have a web page with multiple buttons, and each button represents a different action. When a button is clicked, you want to display a message indicating which button was clicked.
Here’s a sample code snippet that demonstrates this application:
<!DOCTYPE html> <html> <head> <title>Button Click Example</title> </head> <body> <button id="btn1">Button 1</button> <button id="btn2">Button 2</button> <button id="btn3">Button 3</button> <script> function handleClick() { console.log("Button clicked:", this.id); } const buttons = document.querySelectorAll("button"); buttons.forEach(function(button) { button.addEventListener("click", handleClick); }); </script> </body> </html>
Explanation:
This application demonstrates how the this keyword can be used to access the context of an event handler within a specific element, allowing you to perform different actions based on the specific button that was clicked.
Quiz with answers about this lesson
Here’s a multiple-choice quiz about the this keyword in JavaScript:
1-What does the this keyword refer to in JavaScript?
a) The current object
b) The global object
c) The context in which a function is executed
d) All of the above
2-When is this determined in JavaScript?
a) During function declaration
b) During function execution
c) During object instantiation
d) During variable assignment
3-What does this refer to in the global scope in a web browser environment?
a) window object
b) document object
c) console object
d) null
4-How can you explicitly set the value of this in a function?
a) Using the bind() method
b) Using the call() method
c) Using the apply() method
d) All of the above
5-What is the value of this in an event handler?
a) The element that triggered the event
b) The event object
c) The window object
d) The document object
Answers:
6-What is the value of this in the global scope when using strict mode?
a) undefined
b) null
c) window object
d) document object
7-How is this determined when a function is called as a method of an object?
a) It refers to the object itself.
b) It refers to the object’s prototype.
c) It refers to the object’s constructor function.
d) It refers to the global object.
8-Which method can be used to create a new function with an explicitly bound this value?
a) bind()
b) apply()
c) call()
d) this()
9-What happens if you call a regular function without any specific binding of this?
a) It refers to the global object.
b) It throws an error.
c) It refers to the previous object that called the function.
d) It refers to the function itself.
10-What is the value of this in an arrow function?
a) It refers to the object that defines the arrow function.
b) It refers to the global object.
c) It cannot be explicitly bound.
d) It refers to the previous object that called the arrow function.
Answers:
11-What is the value of this in a constructor function?
a) It refers to the newly created object.
b) It refers to the constructor function itself.
c) It refers to the global object.
d) It refers to the object that called the constructor function.
12-How can you override the value of this in a function call?
a) By using the new keyword.
b) By using the that keyword.
c) By using the this keyword.
d) By using the self keyword.
13-When using arrow functions, what is the value of this determined by?
a) It is determined by the context in which the arrow function is defined.
b) It is determined by the context in which the arrow function is called.
c) It is always set to the global object.
d) It is always set to undefined.
14-What happens if you use the bind() method with a function that has already been explicitly bound?
a) It throws an error.
b) It overrides the previous binding and creates a new binding.
c) It has no effect and maintains the existing binding.
d) It sets this to the global object.
15-What is the value of this in a nested function?
a) It refers to the object that contains the nested function.
b) It refers to the innermost function.
c) It refers to the global object.
d) It refers to the previous object that called the nested function.
Answers:
16-What does this refer to in an immediately invoked function expression (IIFE)?
a) The global object.
b) The function itself.
c) The parent function that invoked the IIFE.
d) undefined.
17-What is the value of this inside a callback function passed to the forEach() method?
a) The array that forEach() is called on.
b) The callback function itself.
c) The global object.
d) undefined.
18-How can you explicitly set the value of this in an event handler without using bind()?
a) By using the event.target property.
b) By assigning this to a variable before the event handler.
c) By using an arrow function as the event handler.
d) By passing the desired this value as an argument to the event handler.
19-What is the value of this inside a setTimeout callback function?
a) The global object.
b) The setTimeout function itself.
c) The window object.
d) The this value when setTimeout was called.
20-What is the value of this inside a method defined using ES6 class syntax?
a) The class itself.
b) The instance of the class that the method is called on.
c) The global object.
d) undefined.
Answers:
21-What does this refer to in a method defined using ES6 shorthand method syntax?
a) The object that contains the method.
b) The global object.
c) The method itself.
d) undefined.
22-How can you preserve the value of this inside a function when using it as a callback?
a) By using the bind() method.
b) By using the that keyword.
c) By using an arrow function as the callback.
d) By assigning this to a variable before the callback.
23-What is the value of this inside a getter or setter method of an object?
a) The object that the getter or setter is defined on.
b) The global object.
c) The value being retrieved or set.
d) undefined.
24-How can you change the value of this inside an object method?
a) By using the that keyword.
b) By assigning this to a different object.
c) By using the self keyword.
d) By using the this keyword.
25-What is the value of this in a callback function passed to the map() method?
a) The original array.
b) The map() function itself.
c) The global object.
d) undefined.
Answers:
26-What does this refer to inside a static method of a class?
a) The class itself.
b) The instance of the class that the method is called on.
c) The global object.
d) undefined.
27-How can you determine the value of this within a function that is not a method or an event handler?
a) By examining the lexical scope of the function.
b) By using the that keyword.
c) By using the this keyword.
d) By assigning this to a variable before the function.
28-What is the value of this inside a generator function?
a) The generator function itself.
b) The global object.
c) The object that called the generator function.
d) The object returned by the next() method.
29-How can you change the value of this inside a nested function?
a) By using the that keyword.
b) By using the self keyword.
c) By using the this keyword.
d) By assigning this to a different object.
30-What is the value of this inside a promise callback function?
a) The promise object.
b) The global object.
c) The object that called the promise.
d) undefined.
Answers: