← Back to Engine

The `this` Keyword Bindings


Think of this like asking: "WHO is holding the remote control when this function runs?" In JavaScript, the owner changes depending on how the function is called!

👑 The 4 "Who Is This?" Rules (Precedence Order)

When JavaScript figures out what this is, it checks these 4 rules in order from top boss (Rule 1) to last resort (Rule 4):

  1. 1. The Toy Factory Rule (new) 👑 (Highest Boss):
    When you use new Robot(), JavaScript creates a shiny new object and makes this point to that new robot!
  2. 2. The Bossy Rule (Explicit: .call(), .apply(), .bind()) 📢:
    You explicitly command JavaScript: "Hey! Force this to be THIS specific object!"
  3. 3. The Dot Rule (Implicit: dog.bark()) 👈:
    Look at the left side of the dot! When you write dog.bark(), whatever comes before the dot (dog) becomes this.
  4. 4. The Alone Rule (Default) 🌍 (Lowest Priority):
    If a function is called all by itself (like bark()) with no dot and no boss, this defaults to the big global window object (or undefined in strict mode).

💡 DO YOU KNOW? (The Spread Operator ...)

Imagine you have a bag of marbles 🎒. The spread operator (...) opens the bag and pours out every marble individually!

How to use it in code:

  • Combining Lists: [...bag1, ...bag2] joins two arrays into one single list.
  • Passing Arguments: fn(...myArray) unpacks an array into individual inputs for a function.
const firstArgs = ["Welcome"];
const secondArgs = ["!"];
const combined = [...firstArgs, ...secondArgs]; // ["Welcome", "!"]

Arrow Functions & Method Detachment

Arrow functions do NOT have their own this. They inherit this from wherever they were created. Passing regular methods as callbacks (e.g. setTimeout(obj.method, 100)) causes method detachment, losing their object link!


The Challenge: Polyfill Function.prototype.myBind

Implement a custom myBind(context, ...boundArgs) method on Function.prototype. It must:

  1. Return a new function that calls the original function with this set to context.
  2. Support partial application (combining arguments passed during myBind with arguments passed when calling the returned function).