Methods
Methods
Section titled “Methods”Introduction
Section titled “Introduction”Methods are functions that are properties of objects. They can access the object’s other properties via the this keyword.
Shorthand Method Syntax (ES6)
Section titled “Shorthand Method Syntax (ES6)”const user = { name: 'Alice', greet() { // shorthand — no 'function' keyword return `Hi, I'm ${this.name}`; }};
user.greet(); // "Hi, I'm Alice"Traditional Syntax
Section titled “Traditional Syntax”const user = { name: 'Alice', greet: function() { return `Hi, I'm ${this.name}`; }};Arrow Functions as Methods
Section titled “Arrow Functions as Methods”const user = { name: 'Alice', greet: () => { return `Hi, I'm ${this.name}`; // this is NOT user! }};// Arrow functions don't have their own 'this'Method Chaining
Section titled “Method Chaining”const calculator = { value: 0, add(n) { this.value += n; return this; }, subtract(n) { this.value -= n; return this; }, getResult() { return this.value; }};
calculator.add(5).subtract(2).getResult(); // 3Summary
Section titled “Summary”- Methods are functions stored as object properties
- Use shorthand syntax:
methodName() {} - Use
thisto access other properties - Arrow functions don’t bind their own
this