0
0
Javascriptprogramming~15 mins

this in functions in Javascript - Deep Dive

Choose your learning style9 modes available
Overview - this in functions
What is it?
In JavaScript, 'this' is a special word used inside functions to refer to an object. It tells the function what object it belongs to or is working with. The value of 'this' changes depending on how the function is called, not where it is written. Understanding 'this' helps you control which data your functions use.
Why it matters
Without 'this', functions would not know which object they belong to, making it hard to write reusable and organized code. Imagine trying to use a tool without knowing which machine it belongs to; 'this' connects functions to their objects. Without it, JavaScript would be less flexible and harder to manage, especially in big programs.
Where it fits
Before learning 'this', you should understand basic JavaScript functions and objects. After mastering 'this', you can learn about classes, prototypes, and advanced topics like arrow functions and binding methods. 'this' is a key stepping stone to writing clean, object-oriented JavaScript.
Mental Model
Core Idea
'This' is a pointer that tells a function which object it is currently working with, and its value depends on how the function is called.
Think of it like...
Imagine 'this' as a name tag at a party that tells everyone who you are talking about. Depending on where you stand and who you talk to, the name tag points to a different person.
Function Call Context
┌─────────────────────────────┐
│        Function Call         │
│                             │
│  'this' points to the object │
│  that owns or calls the func │
└─────────────┬───────────────┘
              │
  ┌───────────┴───────────┐
  │                       │
Object A calls func()   Object B calls func()
  │                       │
 'this' → Object A       'this' → Object B
Build-Up - 7 Steps
1
FoundationBasic function and object setup
🤔
Concept: Introduce simple functions and objects to see how they relate.
const obj = { name: 'Alice' }; function greet() { return 'Hello!'; } console.log(greet());
Result
Hello!
Understanding simple functions and objects is the first step before adding 'this' to connect them.
2
FoundationUsing 'this' inside object methods
🤔
Concept: 'This' refers to the object that owns the method when called as a method.
const person = { name: 'Bob', sayName: function() { return this.name; } }; console.log(person.sayName());
Result
Bob
Knowing that 'this' inside a method points to the object helps functions access their own data.
3
Intermediate'this' in standalone functions
🤔Before reading on: When calling a normal function alone, do you think 'this' points to the global object or undefined? Commit to your answer.
Concept: 'This' in a regular function call points to the global object (window in browsers) or undefined in strict mode.
function showThis() { return this; } console.log(showThis());
Result
In browsers, logs the global window object; in strict mode, logs undefined.
Understanding that 'this' defaults to the global object or undefined in functions prevents confusion about unexpected values.
4
Intermediate'this' in event handlers and callbacks
🤔Before reading on: In an event handler, does 'this' refer to the element or the global object? Commit to your answer.
Concept: 'This' inside event handlers usually points to the element that triggered the event.
const button = document.createElement('button'); button.textContent = 'Click me'; document.body.appendChild(button); button.addEventListener('click', function() { console.log(this.textContent); });
Result
When clicked, logs 'Click me' because 'this' is the button element.
Knowing 'this' points to the event target helps write interactive web code that reacts to user actions.
5
IntermediateChanging 'this' with call, apply, and bind
🤔Before reading on: Does bind change 'this' permanently or temporarily? Commit to your answer.
Concept: Functions can have their 'this' set explicitly using call, apply, or bind methods.
const obj1 = { name: 'Carol' }; function say() { return this.name; } console.log(say.call(obj1)); const boundSay = say.bind(obj1); console.log(boundSay());
Result
Carol Carol
Understanding how to control 'this' explicitly allows flexible reuse of functions with different objects.
6
Advanced'this' behavior in arrow functions
🤔Before reading on: Does 'this' in arrow functions refer to the calling object or the surrounding scope? Commit to your answer.
Concept: Arrow functions do not have their own 'this'; they use 'this' from the surrounding code where they are defined.
const obj = { name: 'Dave', arrowFunc: () => this.name, regularFunc: function() { return this.name; } }; console.log(obj.arrowFunc()); console.log(obj.regularFunc());
Result
undefined (or global 'this' name) Dave
Knowing arrow functions inherit 'this' prevents bugs when mixing function types inside objects.
7
ExpertCommon pitfalls with 'this' in nested functions
🤔Before reading on: In a nested regular function inside a method, does 'this' refer to the outer object or global? Commit to your answer.
Concept: Nested regular functions lose the outer 'this' and default to global or undefined, causing unexpected behavior.
const obj = { name: 'Eve', method: function() { function inner() { return this.name; } return inner(); } }; console.log(obj.method());
Result
undefined or global name, not 'Eve'
Understanding this behavior helps avoid bugs and shows why arrow functions or binding are needed in nested functions.
Under the Hood
'This' is a special keyword that is set at the time a function is called, not when it is defined. The JavaScript engine determines the value of 'this' based on the call site: if called as a method, 'this' is the object before the dot; if called as a plain function, 'this' is the global object or undefined in strict mode; if called with call/apply/bind, 'this' is explicitly set; arrow functions capture 'this' from their defining scope.
Why designed this way?
JavaScript was designed to be flexible and dynamic, allowing functions to be reused with different objects. Setting 'this' at call time rather than definition time supports this flexibility. Arrow functions were later added to fix common confusion by lexically binding 'this'. Other languages often bind 'this' differently, but JavaScript's approach fits its prototype-based and functional style.
Call Site Determines 'this'

┌───────────────┐
│ Function Call │
└───────┬───────┘
        │
        ▼
┌─────────────────────────────┐
│ Is function called as method?│
├─────────────┬───────────────┤
│ Yes         │ No            │
│             │               │
▼             ▼               ▼
'this' = object before dot  'this' = global or undefined
or explicit via call/apply/bind
or arrow function uses lexical 'this'
Myth Busters - 4 Common Misconceptions
Quick: Does 'this' always point to the object where the function is written? Commit to yes or no.
Common Belief:Many think 'this' always points to the object where the function is defined.
Tap to reveal reality
Reality:'This' depends on how the function is called, not where it is written.
Why it matters:Assuming 'this' is fixed by definition leads to bugs where functions behave differently depending on call context.
Quick: In arrow functions, does 'this' behave like in regular functions? Commit to yes or no.
Common Belief:Some believe arrow functions have their own 'this' like regular functions.
Tap to reveal reality
Reality:Arrow functions do not have their own 'this'; they use 'this' from the surrounding scope.
Why it matters:Misunderstanding arrow functions causes unexpected 'this' values, especially in object methods.
Quick: Does binding a function with bind() change 'this' forever? Commit to yes or no.
Common Belief:Binding a function permanently changes 'this' for all future calls.
Tap to reveal reality
Reality:Bind creates a new function with fixed 'this', but the original function remains unchanged.
Why it matters:Confusing bind's effect can cause unexpected behavior when reusing functions or debugging.
Quick: Does 'this' in event handlers always point to the global object? Commit to yes or no.
Common Belief:Some think 'this' in event handlers is always the global object.
Tap to reveal reality
Reality:'This' in event handlers points to the element that triggered the event.
Why it matters:Wrong assumptions break interactive code that depends on the event target.
Expert Zone
1
'This' is not a variable or a value stored anywhere; it is a keyword resolved dynamically at call time.
2
Arrow functions capture 'this' from the lexical scope, which can be the global object or undefined if not inside another function.
3
Using bind on arrow functions has no effect because their 'this' is fixed at definition.
When NOT to use
'This' is not useful in pure functional programming styles where functions avoid side effects and object state. In such cases, prefer passing explicit parameters. Also, avoid 'this' in asynchronous callbacks without proper binding or arrow functions to prevent losing context.
Production Patterns
In real-world code, 'this' is often managed using arrow functions to keep context, or bind to fix 'this' in callbacks. Classes use 'this' to refer to instance properties. Frameworks like React use 'this' in class components, but hooks reduce reliance on it. Event handlers rely on 'this' to access DOM elements.
Connections
Object-oriented programming
'This' is the foundation for referring to the current object in OOP.
Understanding 'this' helps grasp how methods access and modify object data, a core OOP idea.
Lexical scope
'This' in arrow functions is linked to lexical scope, unlike regular functions.
Knowing lexical scope clarifies why arrow functions behave differently with 'this' and prevents common bugs.
Context switching in linguistics
Both 'this' in programming and context in language depend on the situation to determine meaning.
Recognizing that meaning depends on context in language helps understand how 'this' changes meaning based on call site.
Common Pitfalls
#1Losing 'this' in nested functions
Wrong approach:const obj = { name: 'Anna', greet: function() { function inner() { return this.name; } return inner(); } }; console.log(obj.greet());
Correct approach:const obj = { name: 'Anna', greet: function() { const inner = () => this.name; return inner(); } }; console.log(obj.greet());
Root cause:Regular nested functions have their own 'this' which defaults to global or undefined, losing the outer object's context.
#2Using arrow functions as object methods
Wrong approach:const obj = { name: 'Ben', sayName: () => this.name }; console.log(obj.sayName());
Correct approach:const obj = { name: 'Ben', sayName: function() { return this.name; } }; console.log(obj.sayName());
Root cause:Arrow functions do not have their own 'this', so they do not work as methods needing object context.
#3Forgetting to bind 'this' in callbacks
Wrong approach:const obj = { name: 'Cara', greet: function() { setTimeout(function() { console.log(this.name); }, 1000); } }; obj.greet();
Correct approach:const obj = { name: 'Cara', greet: function() { setTimeout(() => { console.log(this.name); }, 1000); } }; obj.greet();
Root cause:Regular functions in callbacks lose 'this' context; arrow functions or bind keep the correct 'this'.
Key Takeaways
'This' is a dynamic keyword that points to the object owning or calling a function, not where the function is written.
The value of 'this' depends on how a function is called: as a method, standalone, with call/apply/bind, or as an arrow function.
Arrow functions do not have their own 'this'; they inherit it from the surrounding scope, which changes how they behave inside objects.
Misunderstanding 'this' leads to common bugs, especially in nested functions and callbacks, but using arrow functions or bind can fix these issues.
Mastering 'this' is essential for writing clear, reusable, and bug-free JavaScript code, especially in object-oriented and event-driven programming.