Module 27 : The this Keyword.
📘🧠 Concept
🔹 What is this?
In JavaScript, this is a keyword that refers to the object it belongs to, depending on how a function is called. Its value is determined at runtime.
Think of this as a context reference, not a fixed value. It doesn’t refer to the function itself or its lexical scope — but to the object that is invoking the function.
Different this Bindings
Context
Value of this
Global Scope
Global object (window in browser, global in Node.js)
Object Method
The object that owns the method
Function (non-strict mode)
Global object
Function (strict mode)
undefined
Arrow Function
Lexical scope (this from surrounding code)
Event Handler
The DOM element triggering the event
Class Method
The instance of the class
📌 Section 1: this in Global Context
javascript code
console.log(this); // In browser: window
🧠 Explanation:
In browsers, the global object is window. When not inside a function or method, this refers to the global object.
📌 Section 2: this Inside Regular Function
javascript code
function show() { console.log(this); } show(); // In non-strict mode: window
🔬 With strict mode:
javascript code
"use strict"; function show() { console.log(this); // undefined } show();
💡 Research Insight:
ECMAScript 5 introduced "use strict" which changes how this behaves in functions — from pointing to window to undefined (preventing accidental global object usage).
📌 Section 3: this in Object Methods
javascript code
const person = { name: "Rehana", greet() { console.log("Hello, " + this.name); } }; person.greet(); // Hello, Rehana
🧠 Explanation:
Here this refers to the person object because greet() is being called as a method of that object.
📌 Section 4: this with Arrow Functions
javascript code
const person = { name: "Rehana", greet: () => { console.log("Hello, " + this.name); } }; person.greet(); // Hello, undefined
✅ Correct Arrow Usage Inside a Method
javascript code
const person = { name: "Rehana", greet() { const inner = () => { console.log("Hello, " + this.name); }; inner(); } }; person.greet(); // Hello, Rehana
🔍 Why?
Arrow functions do not bind their own this; they inherit it from the surrounding context.
📌 Section 5: this in Event Listeners
javascript code
document.querySelector("#btn").addEventListener("click", function () { console.log(this); // refers to #btn });
Arrow function version:
javascript code
document.querySelector("#btn").addEventListener("click", () => { console.log(this); // refers to outer lexical context (likely window) });
📌 Section 6: Explicit Binding with call(), apply(), and bind()
javascript code
function showCity() { console.log(this.city); } const location = { city: "Delhi" }; showCity.call(location); // Delhi showCity.apply(location); // Delhi const boundFunc = showCity.bind(location); boundFunc(); // Delhi
🔬 Research:
call() and apply() immediately invoke the function.
bind() returns a new function with permanently bound this.
💻 Methods & Use Cases
✅ 1. Constructor Functions and this
javascript code
function Car(make, model) { this.make = make; this.model = model; } const myCar = new Car("Toyota", "Corolla"); console.log(myCar.make); // Toyota
✅ 2. Classes and this
javascript code
class User { constructor(name) { this.name = name; } greet() { console.log("Hi, " + this.name); } } const u = new User("Rehana"); u.greet(); // Hi, Rehana
1 : Track this in Multiple Contexts
Create a webpage with buttons. Attach event listeners using both normal functions and arrow functions. Print the value of this.
Expected Outcome:
Normal function should print the button.
Arrow function should print window.
html
code
<button id="btn1">Button 1</button> <script> document.getElementById("btn1").addEventListener("click", function () { console.log("Normal function this:", this); // Button }); document.getElementById("btn1").addEventListener("click", () => { console.log("Arrow function this:", this); // Window }); </script>
2 : Track Using bind() to Fix this
Objective: Prevent context loss in event handler
javascript code
function Timer() { this.seconds = 0; setInterval(function () { this.seconds++; console.log(this.seconds); // NaN or error }, 1000); } new Timer();
Fix using bind:
javascript code
function Timer() { this.seconds = 0; setInterval(function () { this.seconds++; console.log(this.seconds); }.bind(this), 1000); } new Timer();
🧠 Summary Table
Function Type
this Behavior
Regular
Determined by how function is called
Method
Refers to the calling object
Arrow
Inherits from lexical scope
Event Handler
Refers to DOM element (with regular function)
Constructor
Refers to newly created object
🧠 Exercises
✅ Exercise 1:
What will the following log?
javascript code
const obj = { val: 10, getVal: function () { return this.val; } }; const val = obj.getVal; console.log(val()); // ?
Answer: undefined (in strict mode) or window.val (in non-strict mode)
✅ Exercise 2:
Fix the above code to always return 10, regardless of how getVal is called.
Solution:
javascript code
const getVal = obj.getVal.bind(obj); console.log(getVal()); // 10
Research Insights
Lexical this (Arrow functions) introduced in ES6 help avoid confusion in nested scopes.
Using bind() is cleaner in older codebases, while arrow functions are preferred in modern JavaScript.
Incorrect this binding is a common source of bugs in JavaScript, especially in asynchronous callbacks and event handling.
📘 Summary
this depends on how a function is called, not where it is defined.
Arrow functions inherit this from the outer context — they do not create their own this.
Use bind, call, and apply to explicitly set this.
Understanding this is crucial when working with OOP, event handling, and callbacks in JavaScript.
Checklist
✔ Understand the dynamic nature of this
✔ Identify the value of this in various contexts
✔ Use call, apply, and bind to control this
✔ Use arrow functions correctly with this
✔ Completed exercises for practical understanding
No comments:
Post a Comment