Object Methods & this Keyword
Objects can have methods — functions that belong to the object. The 'this' keyword refers to the object the method is called on, allowing methods to access the object's own properties.
this Keyword Rules
- In an object method — this = the object that owns the method
- Regular function — this = window (browser) or undefined (strict mode)
- Arrow function — this = inherited from surrounding scope (lexical this). No own this!
- ⚠️ Arrow in object method — Don't use! this won't point to the object
- Event handler — this = the element that triggered the event
- call/apply/bind — Manually set this to any object
this Keyword Code
// Object methods
const user = {
name: "Alice",
age: 25,
// Regular function method — this = user
greet() {
console.log(`Hi, I'm ${this.name}, ${this.age} years old.`);
},
// Method shorthand (same as greet: function() { })
getInfo() {
return { name: this.name, age: this.age };
}
};
user.greet(); // "Hi, I'm Alice, 25 years old."
console.log(user.getInfo()); // { name: "Alice", age: 25 }
// ❌ Arrow function loses 'this'
const broken = {
name: "Bob",
greet: () => {
console.log(this.name); // undefined! Arrow has no own 'this'
}
};
// ✅ Use regular function for methods
const correct = {
name: "Bob",
greet() {
console.log(this.name); // "Bob" ✅
}
};
correct.greet();
// call/apply/bind
function introduce(greeting) {
console.log(`${greeting}, I'm ${this.name}`);
}
const alice = { name: "Alice" };
const bob = { name: "Bob" };
introduce.call(alice, "Hello"); // "Hello, I'm Alice"
introduce.call(bob, "Hey"); // "Hey, I'm Bob"
const aliceIntro = introduce.bind(alice);
aliceIntro("Hi"); // "Hi, I'm Alice"Tip
Tip
Use method shorthand in objects: greet() { } instead of greet: function() { }. It's cleaner, and the method name appears in stack traces for better debugging. This is the standard convention in modern JavaScript.
Priority: new > explicit > implicit > default. Arrow = lexical.
Common Mistake
Warning
Extracting a method from an object loses 'this'. const greetFn = user.greet; greetFn() — 'this' is now undefined (strict mode). Fix with bind: const greetFn = user.greet.bind(user); or call directly: user.greet().
Practice Task
Note
Build a calculator object: (1) Properties: result (starts at 0). (2) Methods: add, subtract, multiply, reset (each modifies this.result). (3) Make methods return 'this' for chaining: calc.add(5).multiply(3).result.
Quick Quiz
Key Takeaways
- Objects can have methods — functions that belong to the object.
- In an object method — this = the object that owns the method
- Regular function — this = window (browser) or undefined (strict mode)
- Arrow function — this = inherited from surrounding scope (lexical this). No own this!