A **method** is a function that is a property of an object. It typically uses `this` to refer to the object it belongs to. The **shorthand method** syntax (`greet() {}`) is preferred over assigning function expressions. Arrow functions as methods are problematic because they don't bind `this`.
1Understanding Object Methods
A method is a function that is a property of an object. It typically uses this to refer to the object it belongs to. The shorthand method syntax (greet() {}) is preferred over assigning function expressions. Arrow functions as methods are problematic because they don't bind this.
Never use arrow functions as object methods when you need 'this' to refer to the object.
const counter = {
count: 0,
increment() { this.count++; },
decrement() { this.count--; },
reset() { this.count = 0; },
getValue() { return this.count; }
};
counter.increment();
counter.increment();
counter.increment();
counter.decrement();
console.log(counter.getValue()); // 22Practical Example
Here is a real-world application of Object Methods showing how it is used in production JavaScript code.
// 'this' problem with arrow functions
const obj = {
name: 'Alice',
greetGood() { return `Hello, ${this.name}`; }, // OK
greetBad: () => `Hello, ${this.name}`, // undefined!
};
console.log(obj.greetGood()); // Hello, Alice
console.log(obj.greetBad()); // Hello, undefined3Best Practices
Follow these guidelines when working with Object Methods:
1. Use shorthand method syntax
2. Never use arrow functions as methods needing 'this'
3. Extract complex logic to standalone functions and call them from methods
Tip: Never use arrow functions as object methods when you need 'this' to refer to the object.
const counter = {
count: 0,
increment() { this.count++; },
decrement() { this.count--; },
reset() { this.count = 0; },
getValue() { return this.count; }
};
counter.increment();
counter.increment();
counter.increment();
counter.decrement();
console.log(counter.getValue()); // 2