68. Object Methods and this
A method is a function stored as a property of an object. Methods define the behavior of the object.
Defining Methods
javascript const dog = { name: 'Buddy', weight: 15,
// Method Definition (using ES6 concise method syntax):
bark() {
console.log('Woof! Woof!');
},
// Traditional function expression method:
eat: function(food) {
console.log(`${this.name} is eating ${food}.`);
}
};
dog.bark(); dog.eat('steak');
The this Keyword
Inside an object method, the this keyword refers to the current object (the object the method belongs to). It allows the method to access the object's own properties.
In the dog.eat() example above, this.name refers to dog.name ('Buddy').
Crucial Concept: The value of this is determined dynamically at runtime, depending on how the function is called, not where it is defined (this will be explored further when we discuss arrow functions).