0
0
Javascriptprogramming~15 mins

What this keyword represents in Javascript - Deep Dive

Choose your learning style9 modes available
Overview - What this keyword represents
What is it?
In JavaScript, the keyword 'this' refers to the object that is currently executing the code. It acts like a pointer that tells you which object owns the current function or code block. The value of 'this' can change depending on how and where a function is called. Understanding 'this' helps you write code that behaves correctly in different situations.
Why it matters
Without understanding 'this', your code can behave unpredictably, especially when using functions inside objects or classes. Many bugs and confusion arise because 'this' does not always point to what you expect. Knowing how 'this' works lets you control context, making your programs more reliable and easier to maintain.
Where it fits
Before learning 'this', you should know basic JavaScript functions, objects, and how functions are called. After mastering 'this', you can learn about advanced topics like classes, prototypes, arrow functions, and event handling where 'this' plays a key role.
Mental Model
Core Idea
'This' is a special word that always means the object that owns or calls the current function.
Think of it like...
Imagine you are in a room and you say 'I am here.' The word 'I' changes meaning depending on who says it. Similarly, 'this' changes meaning depending on who is running the code.
Function call context
┌─────────────────────────────┐
│ Object or function calling   │
│          ↓                  │
│        'this' points here    │
└─────────────────────────────┘
Build-Up - 6 Steps
1
FoundationBasic meaning of 'this'
🤔
Concept: 'This' refers to the current object executing the code.
In a simple object with a method, 'this' points to that object. const obj = { name: 'Alice', greet() { return this.name; } }; console.log(obj.greet()); // What does this print?
Result
Alice
Understanding that 'this' points to the object owning the method helps you access object properties inside functions.
2
FoundationGlobal context of 'this'
🤔
Concept: When not inside any object, 'this' points to the global object (window in browsers).
In the global scope or in a regular function, 'this' is the global object. function show() { return this; } console.log(show() === window); // true in browsers
Result
true
Knowing that 'this' defaults to the global object outside of objects prevents confusion about what 'this' means in simple functions.
3
IntermediateChanging 'this' with call and apply
🤔Before reading on: Do you think 'this' can be set manually in JavaScript functions? Commit to yes or no.
Concept: Functions have methods to set 'this' explicitly: call(), apply(), and bind().
You can force 'this' to point to any object when calling a function. function say() { return this.name; } const person = { name: 'Bob' }; console.log(say.call(person)); // Bob console.log(say.apply(person)); // Bob
Result
Bob Bob
Understanding that 'this' can be controlled manually allows flexible function reuse and dynamic context setting.
4
IntermediateArrow functions and lexical 'this'
🤔Before reading on: Does 'this' inside arrow functions behave the same as in regular functions? Commit to yes or no.
Concept: Arrow functions do not have their own 'this'; they use 'this' from the surrounding code.
Unlike regular functions, arrow functions inherit 'this' from where they are defined. const obj = { name: 'Carol', greet: () => this.name }; console.log(obj.greet()); // What is the output?
Result
undefined (or empty string depending on environment)
Knowing arrow functions share 'this' with their surroundings helps avoid bugs when using them inside objects or classes.
5
Advanced'this' in class methods and constructors
🤔Before reading on: In a class method, does 'this' refer to the instance or the class itself? Commit to your answer.
Concept: In classes, 'this' inside methods refers to the instance created by the constructor.
class Person { constructor(name) { this.name = name; } greet() { return this.name; } } const p = new Person('Dave'); console.log(p.greet());
Result
Dave
Understanding 'this' as the instance in classes is key to using object-oriented programming in JavaScript.
6
ExpertCommon pitfalls with 'this' in callbacks
🤔Before reading on: When passing a method as a callback, does 'this' stay bound to the original object? Commit to yes or no.
Concept: When methods are used as callbacks, 'this' can lose its original meaning unless explicitly bound.
const obj = { name: 'Eve', greet() { return this.name; } }; const greetFunc = obj.greet; console.log(greetFunc()); // What happens here? const boundGreet = obj.greet.bind(obj); console.log(boundGreet());
Result
undefined Eve
Knowing that 'this' can lose context in callbacks helps prevent bugs and shows why binding is necessary.
Under the Hood
'This' is a special keyword that is dynamically set at runtime based on how a function is called. JavaScript does not fix 'this' when defining a function; instead, it assigns 'this' when the function runs. The engine looks at the call site to decide what 'this' should be. Arrow functions are an exception because they capture 'this' from their surrounding lexical scope at definition time.
Why designed this way?
JavaScript was designed to be flexible and support multiple programming styles, including functional and object-oriented. Dynamic 'this' allows functions to be reused with different objects easily. Arrow functions were introduced later to fix common confusion by providing lexical 'this'. Other languages fix 'this' differently, but JavaScript's design balances flexibility and complexity.
Call site determines 'this'

┌───────────────┐
│ Function call │
└──────┬────────┘
       │
       ▼
┌───────────────┐
│ Determine 'this'│
│ based on call  │
│ context        │
└──────┬────────┘
       │
       ▼
┌───────────────┐
│ Execute code  │
│ with 'this'   │
└───────────────┘
Myth Busters - 4 Common Misconceptions
Quick: Does 'this' always point to the object where the function is defined? Commit to yes or no.
Common Belief:Many think 'this' always points to the object where the function is written.
Tap to reveal reality
Reality:'This' depends on how the function is called, not where it is defined.
Why it matters:Assuming 'this' is fixed leads to bugs when functions are passed around or called differently.
Quick: Do arrow functions have their own 'this'? Commit to yes or no.
Common Belief:Some believe arrow functions behave like regular functions and have their own 'this'.
Tap to reveal reality
Reality:Arrow functions do not have their own 'this'; they use the 'this' from their surrounding scope.
Why it matters:Misunderstanding this causes unexpected 'undefined' or global values when using arrow functions inside objects.
Quick: When a method is used as a callback, does 'this' automatically stay bound? Commit to yes or no.
Common Belief:People often think methods keep their 'this' even when passed as callbacks.
Tap to reveal reality
Reality:When used as callbacks, methods lose their original 'this' unless explicitly bound.
Why it matters:This causes bugs where methods behave as if called on the global object or undefined.
Quick: Is 'this' the same in strict mode and non-strict mode? Commit to yes or no.
Common Belief:Many believe 'this' behaves the same regardless of strict mode.
Tap to reveal reality
Reality:In strict mode, 'this' is undefined in functions called without an object; in non-strict mode, it is the global object.
Why it matters:Ignoring strict mode differences can cause unexpected errors or security issues.
Expert Zone
1
'This' inside nested functions defaults to the global object unless bound or using arrow functions.
2
Binding 'this' with bind() creates a new function with fixed 'this', useful for event handlers and callbacks.
3
In event listeners, 'this' points to the element receiving the event, which can differ from the surrounding object.
When NOT to use
'This' is not suitable when you want fixed context in callbacks without binding; arrow functions or closures are better. Avoid relying on 'this' in functional programming styles where pure functions are preferred.
Production Patterns
In real-world code, developers use bind() or arrow functions to control 'this' in callbacks. Classes rely on 'this' for instance data. Frameworks like React use arrow functions or hooks to avoid 'this' confusion. Event-driven code carefully manages 'this' to refer to DOM elements.
Connections
Object-oriented programming
'This' is the foundation for referring to the current object instance in OOP.
Understanding 'this' is essential to grasp how objects and classes work in JavaScript and other OOP languages.
Lexical scoping
Arrow functions use lexical scoping for 'this', unlike regular functions.
Knowing lexical scoping helps understand why arrow functions behave differently with 'this' and how closures capture variables.
Pronouns in natural language
'This' acts like a pronoun whose meaning depends on context.
Recognizing 'this' as a context-dependent reference clarifies why its meaning changes and how to track it.
Common Pitfalls
#1Losing 'this' when passing methods as callbacks.
Wrong approach:const obj = { name: 'Sam', greet() { return this.name; } }; setTimeout(obj.greet, 1000);
Correct approach:const obj = { name: 'Sam', greet() { return this.name; } }; setTimeout(obj.greet.bind(obj), 1000);
Root cause:The method loses its object context when passed as a bare function, so 'this' becomes undefined or global.
#2Using arrow functions as object methods expecting 'this' to refer to the object.
Wrong approach:const obj = { name: 'Ann', greet: () => this.name }; console.log(obj.greet());
Correct approach:const obj = { name: 'Ann', greet() { return this.name; } }; console.log(obj.greet());
Root cause:Arrow functions do not have their own 'this', so they use the outer scope's 'this', not the object.
#3Assuming 'this' is the same in strict and non-strict mode.
Wrong approach:'use strict'; function show() { return this; } console.log(show()); // undefined // Without strict mode function show() { return this; } console.log(show()); // window
Correct approach:Always be aware of strict mode and handle 'this' accordingly, using explicit binding or arrow functions.
Root cause:Strict mode changes the default binding of 'this' in functions, which can surprise developers.
Key Takeaways
'This' in JavaScript is a dynamic reference to the object that calls a function, not where the function is defined.
Arrow functions do not have their own 'this'; they inherit it from their surrounding code, which changes how you use them.
Methods lose their 'this' context when passed as callbacks unless explicitly bound, causing common bugs.
Understanding how 'this' works in different contexts like global scope, objects, classes, and events is essential for writing correct JavaScript.
Mastering 'this' unlocks better control over function behavior and object-oriented programming in JavaScript.