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. The Toy Factory Rule (
new) 👑 (Highest Boss):
When you usenew Robot(), JavaScript creates a shiny new object and makesthispoint to that new robot! -
2. The Bossy Rule (Explicit:
.call(),.apply(),.bind()) 📢:
You explicitly command JavaScript: "Hey! Forcethisto be THIS specific object!" -
3. The Dot Rule (Implicit:
dog.bark()) 👈:
Look at the left side of the dot! When you writedog.bark(), whatever comes before the dot (dog) becomesthis. -
4. The Alone Rule (Default) 🌍 (Lowest Priority):
If a function is called all by itself (likebark()) with no dot and no boss,thisdefaults to the big globalwindowobject (orundefinedin 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:
- Return a new function that calls the original function with
thisset tocontext. - Support partial application (combining arguments passed during
myBindwith arguments passed when calling the returned function).