Bird
Raised Fist0
Javascriptprogramming~15 mins

What this keyword represents in Javascript - Deep Dive

Choose your learning style10 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.

Practice

(1/5)
1. What does the this keyword represent inside a regular function in JavaScript when called as a method of an object?
easy
A. The object that owns the method
B. The global object (like window in browsers)
C. The function itself
D. Undefined

Solution

  1. Step 1: Understand method call context

    When a function is called as a method of an object, this refers to that object.
  2. Step 2: Apply to example

    Inside the method, this points to the object owning the method, not the global object or function itself.
  3. Final Answer:

    The object that owns the method -> Option A
  4. Quick Check:

    this in method = owning object [OK]
Hint: In methods, this is the object before the dot [OK]
Common Mistakes:
  • Thinking this always points to global object
  • Confusing this with the function itself
  • Assuming this is undefined in methods
2. Which of the following is the correct way to access this inside an arrow function to refer to the surrounding object?
easy
A. Use this directly inside the arrow function
B. Use this only inside global scope
C. Use this inside a regular function instead
D. Arrow functions do not have their own this, so it inherits from the surrounding scope

Solution

  1. Step 1: Understand arrow function this behavior

    Arrow functions do not have their own this; they inherit it from the surrounding scope.
  2. Step 2: Apply to object method

    Using this inside an arrow function refers to the this of the outer function or object context.
  3. Final Answer:

    Arrow functions do not have their own this, so it inherits from the surrounding scope -> Option D
  4. Quick Check:

    Arrow function this = inherited context [OK]
Hint: Arrow functions inherit this from outside [OK]
Common Mistakes:
  • Assuming arrow functions have their own this
  • Using arrow functions as object methods expecting this to be the object
  • Confusing arrow function this with regular function this
3. Consider the code:
const obj = {
  name: 'Alice',
  greet() {
    console.log(this.name);
  }
};
const greetFunc = obj.greet;
greetFunc();

What will be the output when greetFunc() is called?
medium
A. Alice
B. undefined
C. Error
D. null

Solution

  1. Step 1: Understand function reference assignment

    Assigning obj.greet to greetFunc detaches the method from its object.
  2. Step 2: Call context of greetFunc()

    When called alone, this inside greetFunc is the global object or undefined in strict mode, so this.name is undefined.
  3. Final Answer:

    undefined -> Option B
  4. Quick Check:

    Detached method this = undefined [OK]
Hint: Detached methods lose their object this [OK]
Common Mistakes:
  • Expecting this to still point to the object
  • Thinking it prints the name property
  • Ignoring strict mode effects on this
4. Identify the error in the following code:
const person = {
  name: 'Bob',
  sayName: () => {
    console.log(this.name);
  }
};
person.sayName();
medium
A. this inside arrow function does not refer to person
B. Missing parentheses in method call
C. Syntax error due to arrow function in object
D. name property is not defined

Solution

  1. Step 1: Analyze arrow function this behavior

    Arrow functions do not have their own this; they inherit from the outer scope, which is not person.
  2. Step 2: Effect on console.log(this.name)

    Since this is not person, this.name is undefined or from global scope, not 'Bob'.
  3. Final Answer:

    this inside arrow function does not refer to person -> Option A
  4. Quick Check:

    Arrow function this ≠ object [OK]
Hint: Avoid arrow functions for object methods needing this [OK]
Common Mistakes:
  • Thinking arrow functions bind this to object
  • Assuming syntax error due to arrow function
  • Confusing missing parentheses with this issues
5. You want to create a constructor function Car that sets the make property using this. Which code correctly uses this to assign the property when creating a new car?
hard
A. const Car = (make) => { this.make = make; }; const myCar = new Car('Toyota');
B. function Car(make) { make = this; } const myCar = Car('Toyota');
C. function Car(make) { this.make = make; } const myCar = new Car('Toyota');
D. function Car(make) { this.make = make; } const myCar = Car('Toyota');

Solution

  1. Step 1: Understand constructor function usage

    Constructor functions use this to assign properties to the new object created by new.
  2. Step 2: Check each option

    function Car(make) { this.make = make; } const myCar = new Car('Toyota'); correctly assigns this.make = make and uses new to create an object. function Car(make) { make = this; } const myCar = Car('Toyota'); assigns incorrectly. const Car = (make) => { this.make = make; }; const myCar = new Car('Toyota'); uses arrow function which does not bind this. function Car(make) { this.make = make; } const myCar = Car('Toyota'); calls constructor without new, so this is not the new object.
  3. Final Answer:

    function Car(make) { this.make = make; } const myCar = new Car('Toyota'); -> Option C
  4. Quick Check:

    Constructor this needs new [OK]
Hint: Use new with constructor to bind this correctly [OK]
Common Mistakes:
  • Calling constructor without new
  • Using arrow functions as constructors
  • Assigning make = this instead of this.make = make
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard