Context & Binding

JavaScript 'this' Keyword

The 'this' keyword refers to the object that is executing the current function. Its value is determined by how a function is called, not where it's defined. Understanding 'this' is crucial for object-oriented programming, event handling, and method binding in JavaScript.

How does this work in JavaScript?

this is decided by how a function is called, not where it's written. In obj.method(), this is obj. In a plain call fn(), it's undefined in strict mode. With new, it's the new object. With call, apply or bind, it's whatever you pass. Arrow functions don't have their own this; they use the surrounding one.

const user = {
  name: "Ada",
  greet() { return this.name; },
};
user.greet();                 // "Ada"
const g = user.greet;
g();                          // undefined: lost its object
const bound = user.greet.bind(user);
bound();                      // "Ada"

Learning Journey

1

Basic Context

Global scope, object methods, functions

2

Binding Methods

call, apply, bind functions

3

Arrow Functions

Lexical binding, differences

4

Advanced Patterns

Classes, event handlers, callbacks

Understanding 'this'

The value of 'this' depends on the context in which a function is called. It's not determined by where the function is written, but by how it's invoked. This dynamic binding is what makes 'this' both powerful and sometimes confusing.

Four Binding Rules

1. Default Binding

Function called without context - 'this' refers to global object (window/global)

function sayHello() { console.log(this); }

2. Implicit Binding

Method called on an object - 'this' refers to that object

obj.method(); // this = obj

3. Explicit Binding

Using call(), apply(), or bind() to set 'this' explicitly

func.call(obj); // this = obj

4. New Binding

Constructor function called with 'new' - 'this' refers to new instance

new Constructor(); // this = new object

Priority Order

1

New Binding

Highest Priority

2

Explicit Binding

call, apply, bind

3

Implicit Binding

Object method call

4

Default Binding

Lowest Priority

Arrow Functions

Arrow functions don't follow these rules - they inherit 'this' from enclosing scope.

Basic 'this' Contexts

1. Global Context

In the global scope, 'this' refers to the global object (window in browsers, global in Node.js).

console.log(this === window); // true (in browser)

function globalFunction() {
  console.log(this === window); // true (non-strict mode)
}

globalFunction();

In strict mode, 'this' in global functions is undefined instead of the global object.

2. Object Method Context

When a function is called as a method of an object, 'this' refers to that object.

const user = {
  name: "Alice",
  age: 30,
  
  greet: function() {
    return "Hello, I'm " + this.name; // this = user object
  },
  
  getInfo: function() {
    return {
      name: this.name,
      age: this.age,
      isAdult: this.age >= 18
    };
  }
};

console.log(user.greet()); // "Hello, I'm Alice"
console.log(user.getInfo().isAdult); // true

The object that appears before the dot (.) when calling the method becomes 'this'.

3. Constructor Function Context

When a function is called with 'new', 'this' refers to the newly created instance.

function Animal(name, species) {
  this.name = name;
  this.species = species;
  
  this.introduce = function() {
    return "I'm " + this.name + ", a " + this.species;
  };
  
  this.speak = function(sound) {
    return this.name + " says " + sound;
  };
}

const dog = new Animal("Buddy", "dog");
const cat = new Animal("Whiskers", "cat");

console.log(dog.introduce()); // "I'm Buddy, a dog"
console.log(cat.speak("meow")); // "Whiskers says meow"

The 'new' keyword creates a new object and binds it to 'this' inside the constructor.

Explicit Binding Methods

1. call() Method

Immediately invokes a function with a specific 'this' value and arguments passed individually.

function introduce(greeting, punctuation) {
  return greeting + ", I'm " + this.name + punctuation;
}

const person1 = { name: "Alice" };
const person2 = { name: "Bob" };

// Using call() to set 'this' and pass arguments
const result1 = introduce.call(person1, "Hello", "!");
const result2 = introduce.call(person2, "Hi", ".");

console.log(result1); // "Hello, I'm Alice!"
console.log(result2); // "Hi, I'm Bob."

Syntax: function.call(thisArg, arg1, arg2, ...)

2. apply() Method

Similar to call(), but arguments are passed as an array instead of individually.

function calculateTotal(tax, discount) {
  const subtotal = this.price * this.quantity;
  const taxAmount = subtotal * tax;
  const discountAmount = subtotal * discount;
  return subtotal + taxAmount - discountAmount;
}

const item1 = { price: 10, quantity: 3 };
const item2 = { price: 25, quantity: 2 };

// Using apply() with arguments array
const total1 = calculateTotal.apply(item1, [0.08, 0.05]);
const total2 = calculateTotal.apply(item2, [0.08, 0.10]);

console.log("Item 1 total:", total1); // 30.9
console.log("Item 2 total:", total2); // 49

Syntax: function.apply(thisArg, [arg1, arg2])

Use case: When you have arguments in an array

3. bind() Method

Creates a new function with a permanently bound 'this' value, without invoking it immediately.

const logger = {
  prefix: "[LOG]",
  
  log: function(message, level) {
    const timestamp = new Date().toLocaleTimeString();
    return this.prefix + " " + timestamp + " [" + level + "] " + message;
  }
};

const errorLogger = { prefix: "[ERROR]" };
const debugLogger = { prefix: "[DEBUG]" };

// Create bound functions
const logError = logger.log.bind(errorLogger);
const logDebug = logger.log.bind(debugLogger);

// Use the bound functions
console.log(logError("Database connection failed", "CRITICAL"));
console.log(logDebug("User input validated", "INFO"));

// Partial application with bind
const logInfo = logger.log.bind(logger, "System ready");
console.log(logInfo("INFO")); // Pre-filled message

Key Benefits

Creates a new function that can be called later with consistent 'this' binding.

Arrow Functions & 'this'

Arrow functions don't have their own 'this' binding. They inherit 'this' from the enclosing lexical context, making them useful for preserving context in callbacks.

Regular vs Arrow Functions

const obj = {
  name: "MyObject",
  
  regularMethod: function() {
    console.log("Regular:", this.name);
    
    // Lost context in callback
    setTimeout(function() {
      console.log("Callback:", this.name); // undefined
    }, 100);
    
    // Arrow preserves context
    setTimeout(() => {
      console.log("Arrow:", this.name); // "MyObject"
    }, 200);
  },
  
  arrowMethod: () => {
    console.log("Arrow method:", this.name); // undefined
  }
};

Practical Applications

Event Handlers

Arrow functions preserve the context of the surrounding object when used as event handlers.

Array Methods

Perfect for map, filter, reduce callbacks where you need to access object properties.

Async Operations

Maintain context in setTimeout, Promise chains, and async/await functions.

Common Pitfalls & Solutions

Common Mistakes

Lost Context in Callbacks

// WRONG obj.method = function() { setTimeout(function() { console.log(this.name); // undefined }, 100); };

Regular functions in callbacks lose their 'this' context.

Method Assignment

// WRONG const method = obj.method; method(); // 'this' is lost // CORRECT const boundMethod = obj.method.bind(obj); boundMethod(); // 'this' preserved

Arrow Functions as Methods

// WRONG const obj = { name: "Test", getName: () => this.name // undefined };

Best Practice Solutions

Use Arrow Functions in Callbacks

// CORRECT obj.method = function() { setTimeout(() => { console.log(this.name); // Works! }, 100); };

Store Reference to 'this'

// ALTERNATIVE obj.method = function() { const self = this; setTimeout(function() { console.log(self.name); // Works! }, 100); };

Use bind() for Event Handlers

// CORRECT element.addEventListener('click', obj.handleClick.bind(obj) );

Modern Patterns & Classes

ES6 Classes and 'this'

In ES6 classes, 'this' refers to the instance of the class, similar to constructor functions.

class TaskManager {
  constructor(name) {
    this.name = name;
    this.tasks = [];
  }
  
  addTask(task) {
    this.tasks.push({
      id: this.tasks.length + 1,
      description: task,
      completed: false,
      createdAt: new Date()
    });
    return this; // Enable method chaining
  }
  
  completeTask(id) {
    const task = this.tasks.find(t => t.id === id);
    if (task) {
      task.completed = true;
    }
    return this;
  }
  
  getTasks() {
    return this.tasks;
  }
  
  getCompletedCount() {
    return this.tasks.filter(t => t.completed).length;
  }
  
  // Arrow function as class field (modern syntax)
  getSummary = () => {
    return `${this.name}: ${this.getCompletedCount()}/${this.tasks.length} completed`;
  }
}

const manager = new TaskManager("Work Tasks");
manager.addTask("Review code")
       .addTask("Write tests")
       .completeTask(1);

console.log(manager.getSummary());

Class Benefits

  • • Cleaner syntax than constructor functions
  • • Built-in 'this' binding
  • • Arrow functions as class fields
  • • Inheritance with super()

Best Practices

  • • Use regular methods for instance methods
  • • Use arrow functions for event handlers
  • • Return 'this' for method chaining
  • • Bind methods when passing as callbacks

Essential 'this' Examples

Code Editor

<button id="btn">Click me</button>
<pre id="out"></pre>

Preview

Key Learning Points:

  • • Global context and function calls
  • • Object method binding and arrow function differences
  • • Constructor function 'this' binding
  • • Event handler context differences
  • • call, apply, and bind methods usage
  • • Class-based 'this' binding and method chaining

The this keyword — step by step

1 / 4
1

this is determined at call time, not definition time

Unlike variables (which are lexically scoped), this is determined dynamically — by how a function is called, not where it is defined. This is the root cause of most this-related bugs. The same function can have a different this depending on whether it is called as a method, a standalone function, or with new.

1 of 4
💡Use bind in constructors sparingly
Binding methods in the constructor creates a new function per instance, increasing memory use. Class field arrow functions do the same. For most cases, arrow wrappers in JSX or explicit bind only at the call site is cleaner and easier to reason about.

🎯 Quick Check

Given: const fn = obj.method; fn(); — what is this inside fn?

The this Keyword: summary

Key points

  • Passing a method as a callback (setTimeout(obj.method)) loses its this. Bind it, or wrap it in an arrow function.
  • In DOM event handlers written as regular functions, this is the element.
  • In class methods this is the instance, but detached methods still lose it.
  • Arrow functions are the easiest fix inside callbacks: setTimeout(() => this.tick(), 1000).

Frequently asked questions

›Why is this undefined in my function?

The function was called without an object, often because it was passed as a callback. Use .bind(obj) or an arrow function wrapper.

›What is the difference between call, apply and bind?

call and apply invoke the function immediately with a given this (apply takes the arguments as an array). bind returns a new function with this fixed permanently.