Functions as Object Methods
You'll learn: How storing a function as an object property transforms it into a method that can interact with the object's data.
The Core Idea
When you store a function inside an object as a property, it becomes a method of that object. This isn't just terminology — methods gain special powers. Inside a method, you can use the keyword this to access other properties of the same object, creating a direct connection between the function and its "home" object.
Think of it like giving an employee (function) access to company resources (object properties). Once the function is hired as a method, it gets credentials (this) to work with the company's internal data.
How It Works
const calculator = {
value: 0,
add: function(n) {
this.value = this.value + n;
return this.value;
}
};
calculator.add(5); // 5
calculator.add(3); // 8
Here, add is a method. Inside it, this.value refers to the value property of the calculator object. The method can both read and modify the object's data.
Methods Can Be Added Anytime
const user = {
name: "Alice"
};
user.greet = function() {
return "Hello, " + this.name;
};
user.greet(); // "Hello, Alice"
Functions stored in objects aren't fundamentally different from other functions — they just have access to this when called as methods.
Key Takeaway: When a function is stored as an object property, it becomes a method and can use this to access and modify the object's other properties, creating behavior that's tied to specific data.