JavaScript and TypeScript course · Module 2: Functions, Arrays and Objects

The this Keyword in JavaScript

14 min read ·
In this lesson9

Welcome back to Jurassic Park! Today we will dive deep into one of the most intriguing and sometimes confusing topics in JavaScript: the this keyword. Understanding this is crucial for effective object-oriented programming in JavaScript and for building complex systems like our park management system.

What is this?

The this keyword in JavaScript refers to the object in whose context a function is being executed. You can think of it as the "current workplace" - just like a Jurassic Park employee might work in different locations (e.g., the lab, the T-Rex enclosure, the control center), a function can be executed in different contexts.

The value of this is not determined when the function is defined, but when it is called, which can cause some confusion. The value of this depends on how the function is invoked:

  1. In the global context
  2. As an object method
  3. As a constructor
  4. Using the call(), apply(), or bind() methods
  5. In arrow functions

Let's look at each of these cases.

1. this in Global Context

When this is used in a regular function (not called as an object method, outside strict mode), it refers to the global object: window in the browser and global in Node.js (globalThis is the common name for both). At the top level of a browser script this is also window, but in a Node.js file it is module.exports, an empty object {}, and in ES modules it is undefined.

// In the global scope
console.log(this); // window in the browser, {} (module.exports) in a Node.js file

// In a regular function
function checkGlobalThis() {
  console.log(this); // also window/global object
}

checkGlobalThis();

In strict mode ("use strict";), this in a regular function will be undefined instead of the global object, which helps avoid accidentally creating global variables.

"use strict";

function strictThis() {
  console.log(this); // undefined
}

strictThis();

2. this as an Object Method

When a function is called as a method of an object, this refers to that object. This is one of the most common and intuitive uses of this in JavaScript.

// Object representing a dinosaur
const velociraptor = {
  name: "Blue",
  species: "Velociraptor",
  age: 5,

  // Method using this
  describe: function() {
    console.log(`This ${this.species} is named ${this.name} and is ${this.age} years old.`);
  },

  // Method that modifies dinosaur data
  ageDinosaur: function(years) {
    this.age += years;
    console.log(`${this.name} is now ${this.age} years old.`);
  }
};

// Calling methods
velociraptor.describe(); // "This Velociraptor is named Blue and is 5 years old."
velociraptor.ageDinosaur(2); // "Blue is now 7 years old."

In the example above, this inside the describe and ageDinosaur methods refers to the velociraptor object, allowing the methods to access its properties.

Potential Pitfall: Losing Context

However, be careful - the this context can be lost if you assign a method to another variable and call it as a regular function:

const velociraptor = {
  name: "Blue",
  describe: function() {
    console.log(`Hi, I'm ${this.name}!`);
  }
};

// Calling as a method - this refers to velociraptor
velociraptor.describe(); // "Hi, I'm Blue!"

// But when we assign the method to a variable...
const describeDino = velociraptor.describe;

// ...and call it as a regular function
describeDino(); // "Hi, I'm undefined!"
// (or "Hi, I'm !" if a global name variable exists)

This is a common problem when passing methods as callbacks:

const trex = {
  name: "Rex",
  roar: function() {
    console.log(`${this.name} roars loudly!`);
  }
};

// Direct call works
trex.roar(); // "Rex roars loudly!"

// But as a callback after 1 second...
setTimeout(trex.roar, 1000); // this does not point to trex, so the name Rex will not appear

// Solution (one way) is to use an arrow function or bind():
setTimeout(() => trex.roar(), 1000); // "Rex roars loudly!"
setTimeout(trex.roar.bind(trex), 1000); // "Rex roars loudly!"

3. this in Constructors

When a function is called with the new operator (as a constructor), this refers to the newly created object. This is a fundamental mechanism for creating object instances in JavaScript.

// Constructor function for dinosaurs
function Dinosaur(name, species, age) {
  // 'this' refers to the newly created object
  this.name = name;
  this.species = species;
  this.age = age;

  this.describe = function() {
    console.log(`${this.name} is a ${this.species} aged ${this.age} years.`);
  };
}

// Creating new instances
const blue = new Dinosaur("Blue", "Velociraptor", 5);
const rex = new Dinosaur("Rex", "Tyrannosaurus", 8);

blue.describe(); // "Blue is a Velociraptor aged 5 years."
rex.describe(); // "Rex is a Tyrannosaurus aged 8 years."

// Let's modify Blue's age
blue.age = 6;
blue.describe(); // "Blue is a Velociraptor aged 6 years."

In modern JavaScript (ES6+), instead of constructor functions we often use classes, which provide a cleaner syntax for doing the same thing:

// ES6 class for dinosaurs
class Dinosaur {
  constructor(name, species, age) {
    this.name = name;
    this.species = species;
    this.age = age;
  }

  // Methods are automatically added to the prototype
  describe() {
    console.log(`${this.name} is a ${this.species} aged ${this.age} years.`);
  }

  // Method that changes the age
  growOlder(years = 1) {
    this.age += years;
    console.log(`${this.name} is now ${this.age} years old.`);
  }
}

// Creating instances
const trixie = new Dinosaur("Trixie", "Triceratops", 7);
trixie.describe(); // "Trixie is a Triceratops aged 7 years."
trixie.growOlder(3); // "Trixie is now 10 years old."

4. Controlling this: call(), apply(), and bind()

JavaScript offers three methods that allow you to explicitly control the value of this when calling a function:

call()

The call() method calls a function with a specified this value and arguments passed individually:

function examineSpecimen(testType, labNumber) {
  console.log(`Examining ${this.species} named ${this.name}...`);
  console.log(`Test type: ${testType}, Laboratory: ${labNumber}`);
}

const specimen = {
  name: "Echo",
  species: "Velociraptor",
  age: 3
};

// Calling the function with 'this' set to specimen
examineSpecimen.call(specimen, "DNA", "Lab-A");
// "Examining Velociraptor named Echo..."
// "Test type: DNA, Laboratory: Lab-A"

apply()

The apply() method works similarly to call(), but arguments are passed as an array:

// Same function
function examineSpecimen(testType, labNumber) {
  console.log(`Examining ${this.species} named ${this.name}...`);
  console.log(`Test type: ${testType}, Laboratory: ${labNumber}`);
}

// Calling with arguments in an array
examineSpecimen.apply(specimen, ["Behavioral", "Lab-B"]);
// "Examining Velociraptor named Echo..."
// "Test type: Behavioral, Laboratory: Lab-B"

bind()

The bind() method creates a new function with a permanently assigned this value:

const dinosaur = {
  name: "Delta",
  species: "Velociraptor"
};

function makeSound(sound) {
  console.log(`${this.name} makes a sound: ${sound}!`);
}

// Creating a new function with 'this' bound to dinosaur
const dinosaurSound = makeSound.bind(dinosaur);

// Now we can call this function multiple times
dinosaurSound("Growling"); // "Delta makes a sound: Growling!"
dinosaurSound("Hissing"); // "Delta makes a sound: Hissing!"

// We can also pre-bind arguments
const deltaRoar = makeSound.bind(dinosaur, "ROAR");
deltaRoar(); // "Delta makes a sound: ROAR!"

Practical Example: Dinosaur Tracking System

The following example shows how different methods of controlling this can be used to create a flexible monitoring system:

const dinoMonitoringSystem = {
  activeDinosaurs: [],

  // Register a new dinosaur
  registerDinosaur: function(dinosaur) {
    this.activeDinosaurs.push(dinosaur);
    console.log(`Registered new dinosaur: ${dinosaur.name} (${dinosaur.species})`);
  },

  // Find a dinosaur by name
  findDinosaurByName: function(name) {
    return this.activeDinosaurs.find(dino => dino.name === name);
  },

  // Trigger an alert procedure
  triggerAlert: function(message) {
    console.log(`SYSTEM ALERT: ${message}`);

    // Notify about all active dinosaurs
    this.activeDinosaurs.forEach(function(dino) {
      console.log(`- ${dino.name} (${dino.species}) in sector ${dino.sector}`);
    });
  }
};

// Dinosaur class with a movement method
class Dinosaur {
  constructor(name, species, sector) {
    this.name = name;
    this.species = species;
    this.sector = sector;
    this.status = "calm";
  }

  move(newSector, monitoringSystem) {
    // We can pass monitoringSystem as a parameter
    console.log(`${this.name} is moving from sector ${this.sector} to sector ${newSector}`);
    this.sector = newSector;

    // Or use call() to invoke a method with the proper context
    const alertMessage = `Dinosaur ${this.name} entered sector ${newSector}!`;
    monitoringSystem.triggerAlert.call(monitoringSystem, alertMessage);
  }

  // Method that changes dinosaur status
  updateStatus(newStatus) {
    this.status = newStatus;
    console.log(`Dinosaur ${this.name} status changed to: ${this.status}`);
    return this;
  }
}

// Initialize system and dinosaurs
const rex = new Dinosaur("Rex", "Tyrannosaurus", "A");
const blue = new Dinosaur("Blue", "Velociraptor", "B");
const delta = new Dinosaur("Delta", "Velociraptor", "B");

// Register dinosaurs in the system
dinoMonitoringSystem.registerDinosaur(rex);
dinoMonitoringSystem.registerDinosaur(blue);
dinoMonitoringSystem.registerDinosaur(delta);

// Move a dinosaur
blue.move("C", dinoMonitoringSystem);

// Method chaining (thanks to return this)
rex.updateStatus("agitated").updateStatus("aggressive");

// Using bind() to create a function with predefined 'this'
const checkRexStatus = function() {
  console.log(`T-Rex status: ${this.status}`);
};

const boundCheckStatus = checkRexStatus.bind(rex);
boundCheckStatus(); // "T-Rex status: aggressive"

5. this in Arrow Functions

Arrow functions, introduced in ES6, handle this differently than traditional functions. They do not have their own this; instead, they "inherit" this from the surrounding lexical scope.

const parkSystem = {
  name: "Jurassic Park",
  dinosaurs: ["T-Rex", "Velociraptor", "Triceratops"],

  // Method using an arrow function
  listDinosaurs: function() {
    console.log(`${this.name} contains the following dinosaurs:`);

    // Arrow function preserves 'this' from the listDinosaurs scope
    this.dinosaurs.forEach(dino => {
      console.log(`- ${dino} in park ${this.name}`);
    });

    // For comparison - a traditional function would lose 'this' context
    /*
    this.dinosaurs.forEach(function(dino) {
      // 'this' refers to the global object or is undefined in strict mode
      console.log(`- ${dino} in park ${this.name}`); // this.name would be undefined
    });
    */
  }
};

parkSystem.listDinosaurs();
// "Jurassic Park contains the following dinosaurs:"
// "- T-Rex in park Jurassic Park"
// "- Velociraptor in park Jurassic Park"
// "- Triceratops in park Jurassic Park"

Arrow functions are especially useful when you want to preserve the this context in nested functions, callbacks, or asynchronous programming.

Practical Example: Monitoring System with Timers

class DinosaurMonitor {
  constructor(name, species) {
    this.name = name;
    this.species = species;
    this.status = "Normal";
    this.lastUpdated = new Date();
    this.checkInterval = null;
  }

  // Start monitoring with regular status checks
  startMonitoring() {
    console.log(`Starting monitoring for dinosaur: ${this.name}`);

    // Arrow function preserves the 'this' context
    this.checkInterval = setInterval(() => {
      this.checkStatus();
    }, 5000);

    // If we used a regular function, we would lose context:
    /*
    this.checkInterval = setInterval(function() {
      // 'this' here refers to the global object, not to the DinosaurMonitor instance
      this.checkStatus(); // Error: this.checkStatus is not a function
    }, 5000);
    */
  }

  // Check dinosaur status
  checkStatus() {
    const now = new Date();
    const timeSinceLastUpdate = (now - this.lastUpdated) / 1000; // in seconds

    console.log(`Checking status of dinosaur ${this.name} (${this.species})...`);
    console.log(`Last updated: ${timeSinceLastUpdate.toFixed(1)} seconds ago`);
    console.log(`Status: ${this.status}`);

    this.lastUpdated = now;

    // Simulate status change (in a real system, sensor data would go here)
    if (Math.random() < 0.3) {
      const possibleStatuses = ["Normal", "Agitated", "Resting", "Feeding", "Aggressive"];
      this.status = possibleStatuses[Math.floor(Math.random() * possibleStatuses.length)];
      console.log(`New status: ${this.status}`);
    }
  }

  // Stop monitoring
  stopMonitoring() {
    if (this.checkInterval) {
      clearInterval(this.checkInterval);
      this.checkInterval = null;
      console.log(`Stopped monitoring dinosaur: ${this.name}`);
    }
  }
}

// Create and start a monitor
const blueMonitor = new DinosaurMonitor("Blue", "Velociraptor");
blueMonitor.startMonitoring();

// Stop the monitor after 20 seconds
setTimeout(() => {
  blueMonitor.stopMonitoring();
}, 20000);

Common Pitfalls with this

The this keyword can be a source of many bugs in JavaScript. Here are some common pitfalls and how to avoid them:

1. Losing Context in Nested Functions

const dinosaur = {
  name: "Rex",
  behaviors: ["hunting", "resting", "running"],

  logBehaviors: function() {
    // 'this' here refers to 'dinosaur'
    console.log(`Dinosaur ${this.name} exhibits the following behaviors:`);

    // Problem: 'this' in the forEach function refers to the global object
    this.behaviors.forEach(function(behavior) {
      // 'this.name' is undefined
      console.log(`- ${this.name} likes ${behavior}`);
    });
  }
};

dinosaur.logBehaviors();
// "Dinosaur Rex exhibits the following behaviors:"
// "- undefined likes hunting"
// "- undefined likes resting"
// "- undefined likes running"

Solutions:

  1. Use an arrow function:
const dinosaur = {
  name: "Rex",
  behaviors: ["hunting", "resting", "running"],

  logBehaviors: function() {
    console.log(`Dinosaur ${this.name} exhibits the following behaviors:`);

    // Arrow function preserves 'this' from the surrounding scope
    this.behaviors.forEach(behavior => {
      console.log(`- ${this.name} likes ${behavior}`);
    });
  }
};
  1. Store a reference to this in a variable:
const dinosaur = {
  name: "Rex",
  behaviors: ["hunting", "resting", "running"],

  logBehaviors: function() {
    console.log(`Dinosaur ${this.name} exhibits the following behaviors:`);

    // Store reference to 'this' in a variable 'self' or 'that'
    const self = this;
    this.behaviors.forEach(function(behavior) {
      console.log(`- ${self.name} likes ${behavior}`);
    });
  }
};
  1. Use the bind() method:
const dinosaur = {
  name: "Rex",
  behaviors: ["hunting", "resting", "running"],

  logBehaviors: function() {
    console.log(`Dinosaur ${this.name} exhibits the following behaviors:`);

    // Using bind() to attach 'this'
    this.behaviors.forEach(function(behavior) {
      console.log(`- ${this.name} likes ${behavior}`);
    }.bind(this));
  }
};

2. Methods as Callbacks

When an object method is passed as a callback, it loses its this context:

class DinosaurTracker {
  constructor(name) {
    this.name = name;
    this.tracked = false;
  }

  startTracking() {
    this.tracked = true;
    console.log(`Started tracking dinosaur ${this.name}`);
  }
}

const blueTracker = new DinosaurTracker("Blue");

// Works correctly
blueTracker.startTracking();

// Doesn't work - 'this' does not refer to blueTracker
setTimeout(blueTracker.startTracking, 1000); // this does not point to blueTracker

Solutions:

  1. Use an arrow function:
setTimeout(() => blueTracker.startTracking(), 1000);
  1. Use bind():
setTimeout(blueTracker.startTracking.bind(blueTracker), 1000);

Advanced Example: Park Management System

Below is a more complex example of a Jurassic Park management system that uses various aspects of the this keyword:

// Main park management system
const parkManagementSystem = {
  parkName: "Jurassic Park",
  status: "operational",
  securityLevel: "normal",

  // Park subsystems
  subsystems: {
    power: { status: "online", output: "100%" },
    security: { status: "active", fences: "operational" },
    visitorCenter: { status: "open", visitors: 120 }
  },

  // System initialization method
  initialize: function() {
    console.log(`Initializing park management system: ${this.parkName}`);

    // Check all subsystems
    this.checkAllSubsystems();

    // Set up regular monitoring
    this.startMonitoring();

    return this;
  },

  // Check subsystem status
  checkAllSubsystems: function() {
    console.log("Checking status of all subsystems...");

    // Using Object.entries and arrow function to preserve 'this' context
    Object.entries(this.subsystems).forEach(([name, system]) => {
      console.log(`- Subsystem ${name}: ${system.status}`);

      // Call specific checks for each subsystem
      this[`check${name.charAt(0).toUpperCase() + name.slice(1)}`]();
    });
  },

  // Specific check methods for each subsystem
  checkPower: function() {
    const powerSystem = this.subsystems.power;
    console.log(`  Checking power: ${powerSystem.status}, Output: ${powerSystem.output}`);
  },

  checkSecurity: function() {
    const securitySystem = this.subsystems.security;
    console.log(`  Checking security: ${securitySystem.status}, Fences: ${securitySystem.fences}`);
  },

  checkVisitorCenter: function() {
    const visitorSystem = this.subsystems.visitorCenter;
    console.log(`  Checking visitor center: ${visitorSystem.status}, Visitors: ${visitorSystem.visitors}`);
  },

  // Start regular monitoring
  startMonitoring: function() {
    console.log("Starting regular park monitoring...");

    // Arrow function to preserve 'this' context
    this.monitoringInterval = setInterval(() => {
      this.checkSecurityStatus();
    }, 10000);

    // Simulate a method call after 5 seconds
    setTimeout(() => this.simulateSecurityAlert(), 5000);
  },

  // Check security status
  checkSecurityStatus: function() {
    console.log(`[MONITOR] Park status: ${this.status}, Security level: ${this.securityLevel}`);
  },

  // Simulate a security alert
  simulateSecurityAlert: function() {
    console.log("SIMULATION: Security breach detected in sector B!");

    // Change park status and security level
    this.status = "alert";
    this.securityLevel = "high";
    console.log(`Park status changed to: ${this.status}`);
    console.log(`Security level raised to: ${this.securityLevel}`);

    // Direct status check
    this.checkSecurityStatus();

    // Create an emergency response team using a constructor
    const responseTeam = new EmergencyResponseTeam(this);

    // Pass method as callback while preserving context
    responseTeam.respondToAlert(this.resolveSecurityAlert.bind(this));
  },

  // Resolve security alert
  resolveSecurityAlert: function(report) {
    console.log(`Received report from response team: ${report}`);

    // Restore normal status
    this.status = "operational";
    this.securityLevel = "normal";
    console.log("Security alert resolved.");
    console.log(`Park status restored to: ${this.status}`);

    // Check current status
    this.checkSecurityStatus();
  },

  // Stop monitoring
  stopMonitoring: function() {
    if (this.monitoringInterval) {
      clearInterval(this.monitoringInterval);
      console.log("Park monitoring stopped.");
    }
  }
};

// Constructor for the emergency response team
function EmergencyResponseTeam(park) {
  // 'this' refers to the new object
  this.teamName = "Emergency Response Team";
  this.members = ["Owen Grady", "Claire Dearing", "Dr. Wu"];
  this.assignedPark = park;

  this.respondToAlert = function(callback) {
    console.log(`${this.teamName} responding to alert at park: ${this.assignedPark.parkName}`);

    // Simulate response time
    setTimeout(() => {
      console.log(`${this.teamName} has secured the area and restored fences.`);

      // Call the callback with a report
      if (typeof callback === 'function') {
        callback("Threat neutralized, fences repaired");
      }
    }, 3000);
  };
}

// Initialize and start the system
parkManagementSystem.initialize();

// Stop the system after 20 seconds
setTimeout(() => {
  parkManagementSystem.stopMonitoring();
}, 20000);

Summary and Best Practices

The this keyword is a powerful tool in JavaScript, but it requires understanding how it behaves in different contexts:

  1. In the global context: this is window in the browser and module.exports ({}) in a Node.js file; in a regular function outside strict mode it is the global object (globalThis).

  2. In an object method: this refers to the object that called the method.

  3. In a constructor: this refers to the newly created object.

  4. In arrow functions: this is inherited from the surrounding lexical scope.

  5. With call/apply/bind: this is explicitly specified by the programmer.

Best Practices:

  1. Use arrow functions for callbacks and nested functions to preserve the this context.

  2. Use call(), apply(), or bind() methods when you need to explicitly control the value of this.

  3. Avoid creating methods in constructors; instead, add them to the prototype to avoid code duplication.

  4. Remember that this is determined when the function is called, not when it is defined.

  5. Use ES6 classes instead of traditional constructors for cleaner code.

In the next lesson, we will dive deeper into arrays in JavaScript, which are a key component of managing data collections in our Jurassic Park.

Code for this lesson: index.js
// The 'this' keyword - Jurassic Park
console.log("'this' Laboratory in JavaScript");
console.log("Understanding execution context\n");

// ===========================================
// 1. 'this' BASICS
// ===========================================
console.log("=== 1. What is 'this'? ===");

// 'this' refers to the object in whose context the code is executed

const dinosaur = {
  name: "Tyrannosaurus Rex",
  age: 8,

  roar: function() {
    console.log(`\n${this.name} roars: ROAARRR!`);
    console.log(`   Age: ${this.age} years`);
  }
};

dinosaur.roar(); // 'this' points to the 'dinosaur' object

// ===========================================
// 2. 'this' IN DIFFERENT CONTEXTS
// ===========================================
console.log("\n=== 2. 'this' contexts ===");

// Context 1: Object method
const raptor = {
  name: "Velociraptor",
  speed: 40,

  run: function() {
    console.log(`\n${this.name} running at a speed of ${this.speed} km/h`);
  }
};

raptor.run(); // this = raptor

// Context 2: Global function (strict mode)
function globalFunction() {
  console.log("\nGlobal function - this:", typeof this);
  // In strict mode: undefined
  // Without strict mode: window (browser) or global (Node.js)
}

globalFunction();

// Context 3: Constructor
function Dinosaur(name, species) {
  this.name = name;
  this.species = species;
  this.roar = function() {
    console.log(`${this.name} (${this.species}): ROAARRR!`);
  };
}

const trex = new Dinosaur("Rexy", "T-Rex");
console.log("\nConstructor:");
console.log(`   Name: ${trex.name}`);
console.log(`   Species: ${trex.species}`);
trex.roar();

// ===========================================
// 3. LOSS OF 'this' CONTEXT
// ===========================================
console.log("\n=== 3. Loss of 'this' context ===");

const park = {
  name: "Jurassic Park",
  dinosaurs: ["T-Rex", "Velociraptor", "Triceratops"],

  displayDinosaurs: function() {
    console.log(`\nDinosaurs in ${this.name}:`);

    // PROBLEM: forEach with a traditional function
    // this.dinosaurs.forEach(function(dino) {
    //   console.log(`   - ${dino} from ${this.name}`); // this.name = undefined!
    // });

    // SOLUTION 1: Arrow function
    this.dinosaurs.forEach(dino => {
      console.log(`   - ${dino} from ${this.name}`);
    });
  }
};

park.displayDinosaurs();

// SOLUTION 2: bind()
const park2 = {
  name: "Isla Nublar",
  dinosaurs: ["Stegosaurus", "Brachiosaurus"],

  displayDinosaurs: function() {
    console.log(`\nDinosaurs in ${this.name}:`);

    this.dinosaurs.forEach(function(dino) {
      console.log(`   - ${dino} from ${this.name}`);
    }.bind(this)); // Binding this
  }
};

park2.displayDinosaurs();

// ===========================================
// 4. METHODS: call(), apply(), bind()
// ===========================================
console.log("\n=== 4. Methods: call(), apply(), bind() ===");

const dinoInfo = {
  describe: function(habitat, diet) {
    console.log(`\n${this.name}:`);
    console.log(`   Environment: ${habitat}`);
    console.log(`   Diet: ${diet}`);
  }
};

const dino1 = { name: "T-Rex" };
const dino2 = { name: "Triceratops" };

// call() - a call with an explicit this and arguments
dinoInfo.describe.call(dino1, "Tropical forest", "Carnivore");

// apply() - like call(), but with the arguments in an array
dinoInfo.describe.apply(dino2, ["Savanna", "Herbivore"]);

// bind() - creates a new function with bound this
const describeTRex = dinoInfo.describe.bind(dino1);
describeTRex("Jungle", "Carnivore");

// ===========================================
// 5. ARROW FUNCTIONS AND 'this'
// ===========================================
console.log("\n=== 5. Arrow functions and 'this' ===");

const enclosure = {
  id: "A-7",
  dinosaur: "Velociraptor",

  // Traditional method
  checkTraditional: function() {
    console.log(`\nPaddock ${this.id} (traditional):`);

    setTimeout(function() {
      // console.log(`   Dinosaur: ${this.dinosaur}`); // undefined! this has changed
      console.log("   this.dinosaur = undefined (context lost)");
    }, 100);
  },

  // Solution with an arrow function
  checkArrow: function() {
    console.log(`\nPaddock ${this.id} (arrow):`);

    setTimeout(() => {
      console.log(`   Dinosaur: ${this.dinosaur}`); // Works! Arrow preserves this
    }, 100);
  }
};

enclosure.checkTraditional();

setTimeout(() => {
  enclosure.checkArrow();
}, 150);

// ===========================================
// 6. 'this' IN CONSTRUCTORS AND CLASSES
// ===========================================
console.log("\n=== 6. 'this' in constructors and classes ===");

// Constructor function
function DinosaurPark(name) {
  this.name = name;
  this.dinosaurs = [];

  this.addDinosaur = function(dino) {
    this.dinosaurs.push(dino);
    console.log(`Added ${dino} to ${this.name}`);
  };

  this.getCount = function() {
    return this.dinosaurs.length;
  };
}

const park1 = new DinosaurPark("Jurassic Park");
park1.addDinosaur("T-Rex");
park1.addDinosaur("Velociraptor");
console.log(`Total dinosaurs: ${park1.getCount()}`);

// ES6 Class
class ModernPark {
  constructor(name) {
    this.name = name;
    this.dinosaurs = [];
  }

  addDinosaur(dino) {
    this.dinosaurs.push(dino);
    console.log(`\nAdded ${dino} to ${this.name}`);
  }

  getCount() {
    return this.dinosaurs.length;
  }

  displayAll() {
    console.log(`\n${this.name} - Dinosaur list:`);
    this.dinosaurs.forEach((dino, i) => {
      console.log(`   ${i + 1}. ${dino}`);
    });
  }
}

const park3 = new ModernPark("Isla Nublar");
park3.addDinosaur("Triceratops");
park3.addDinosaur("Stegosaurus");
park3.addDinosaur("Brachiosaurus");
park3.displayAll();
console.log(`Total: ${park3.getCount()}`);

// ===========================================
// 7. PROBLEM: METHOD AS CALLBACK
// ===========================================
console.log("\n=== 7. Problem: method as callback ===");

const securitySystem = {
  level: "HIGH",

  checkSecurity: function() {
    console.log(`Security level: ${this.level}`);
  }
};

// PROBLEM: this will be lost
setTimeout(securitySystem.checkSecurity, 100); // this.level = undefined

// SOLUTION 1: Arrow function wrapper
setTimeout(() => {
  securitySystem.checkSecurity();
}, 150);

// SOLUTION 2: bind()
setTimeout(securitySystem.checkSecurity.bind(securitySystem), 200);

// ===========================================
// 8. COMPLEX EXAMPLE
// ===========================================
console.log("\n=== 8. Park management system - complex example ===");

class JurassicParkManagement {
  constructor(parkName) {
    this.parkName = parkName;
    this.dinosaurs = [];
    this.visitors = 0;
    this.status = "CLOSED";
  }

  openPark() {
    this.status = "OPEN";
    console.log(`\n${this.parkName} - Park open`);
  }

  closePark() {
    this.status = "CLOSED";
    console.log(`\n${this.parkName} - Park closed`);
  }

  addDinosaur(name, species, sector) {
    const dino = { name, species, sector, health: 100 };
    this.dinosaurs.push(dino);
    console.log(`Added ${name} (${species}) to sector ${sector}`);
  }

  addVisitors(count) {
    this.visitors += count;
    console.log(`Added ${count} visitors. Total: ${this.visitors}`);
  }

  checkDinosaur(name) {
    const dino = this.dinosaurs.find(d => d.name === name);
    if (dino) {
      console.log(`\nChecking ${name}:`);
      console.log(`   Species: ${dino.species}`);
      console.log(`   Sector: ${dino.sector}`);
      console.log(`   Health: ${dino.health}%`);
    } else {
      console.log(`Dinosaur not found: ${name}`);
    }
  }

  getDailyReport() {
    console.log(`\nDAILY REPORT - ${this.parkName}`);
    console.log("=".repeat(50));
    console.log(`Status: ${this.status}`);
    console.log(`Dinosaurs: ${this.dinosaurs.length}`);
    console.log(`Visitors: ${this.visitors}`);

    if (this.dinosaurs.length > 0) {
      console.log("\nDinosaur list:");
      this.dinosaurs.forEach((dino, i) => {
        console.log(`  ${i + 1}. ${dino.name} (${dino.species}) - Sector ${dino.sector}`);
      });
    }
  }

  // Method using setTimeout with an arrow function
  scheduleFeeding(dinoName, delay = 1000) {
    console.log(`\n⏰ Feeding scheduled for ${dinoName} in ${delay}ms`);

    setTimeout(() => {
      const dino = this.dinosaurs.find(d => d.name === dinoName);
      if (dino) {
        console.log(`Feeding ${dinoName} in ${this.parkName}`);
        dino.health = Math.min(100, dino.health + 10);
      }
    }, delay);
  }
}

// System demonstration
const management = new JurassicParkManagement("Isla Nublar");

management.openPark();
management.addDinosaur("Rexy", "Tyrannosaurus Rex", "A");
management.addDinosaur("Blue", "Velociraptor", "B");
management.addDinosaur("Trike", "Triceratops", "C");

management.addVisitors(500);
management.addVisitors(300);

management.checkDinosaur("Blue");
management.getDailyReport();

management.scheduleFeeding("Rexy", 500);
management.scheduleFeeding("Blue", 600);

setTimeout(() => {
  console.log("\n--- After feeding ---");
  management.checkDinosaur("Rexy");
  management.checkDinosaur("Blue");

  management.closePark();

  console.log("\nCongratulations! You've mastered the 'this' keyword!");
}, 800);

Docs entries used in this lesson

Spotted a mistake in this lesson?

Check yourself

Answer the questions from this lesson. Pick an answer to see right away whether it is correct.

  1. 1. What does the 'this' keyword mean in JavaScript?

  2. 2. What does 'this' point to inside an object method in JavaScript?

  3. 3. How does 'this' behave in arrow functions?

  4. 4. In what context does 'this' point to the newly created object?

  1. Questionthis Context in JavaScript
  2. Questionthis Value in Object Methods
  3. Questionthis in Arrow Functions
  4. Questionthis Context in Constructors

Useful articles