Week 7: Structuring Data with Objects
Learn to represent complex data using key-value pairs in JavaScript Objects.
Explore Chapter 7Object Methods: Functions as Properties.
When a function is stored as a property of an object, it's called a method. Methods define the actions or behaviors that an object can perform. They often operate on the data contained within the object itself.
Defining Methods
You define a method like any other property, but assign a function as the value.
let calculator = {
value: 0,
add: function(num) { // Traditional function expression
this.value += num; // 'this' refers to the calculator object itself
},
subtract(num) { // Shorthand method syntax (ES6+)
this.value -= num;
},
getValue() { // Shorthand syntax
return this.value;
}
};
Calling Methods
You call methods using dot notation, followed by parentheses () to invoke the function.
console.log(calculator.getValue()); // Output: 0
calculator.add(10);
console.log(calculator.getValue()); // Output: 10
calculator.subtract(3);
console.log(calculator.getValue()); // Output: 7
The this Keyword
Inside an object method defined using traditional syntax or shorthand, the keyword this typically refers to the object the method was called on (e.g., calculator in the example above). This allows methods to access and manipulate the object's own properties (this.value). Arrow functions handle this differently, which we'll discuss later.