1. The this Keyword
The value of this refers to the object that is currently executing the code. However, its value changes depending on where it is called:
Inside a Method:
thisrefers to the object owning the method.Global Scope:
thisrefers to thewindow(the browser).Arrow Functions: Unlike regular functions, arrow functions do not have their own
this. They "borrow" it from the surrounding code.
2. Prototypes
In JavaScript, objects have a hidden property called a Prototype. This is basically a "parent" object where they can inherit methods and properties. This is how JavaScript does inheritance without being a "true" class-based language like Java.
The Code Example
// 1. Understanding 'this' in an Object
const user = {
username: "Gemini_AI",
greet() {
// 'this' refers to the 'user' object
console.log(`Hello, I am ${this.username}`);
}
};
user.greet();
// 2. The Prototype (The "Ancestor" of the object)
function Dog(name) {
this.name = name;
}
// Adding a method to the Prototype so all dogs share it (saves memory)
Dog.prototype.bark = function() {
console.log(`${this.name} says Woof! 🐾`);
};
const myDog = new Dog("Buddy");
const yourDog = new Dog("Max");
myDog.bark();
yourDog.bark();
// 3. 'this' Pitfall (Arrow Functions vs Regular)
const timer = {
seconds: 0,
start() {
// Arrow function keeps the 'this' from the timer object
setInterval(() => {
this.seconds++;
console.log(this.seconds);
}, 1000);
}
};
// timer.start(); // This would count up 1, 2, 3...