Object Methods
👨💼 Objects can contain functions! When a function is a property of an object,
we call it a method.
const calculator = {
add: function (a, b) {
return a + b
},
// Shorthand syntax (preferred):
subtract(a, b) {
return a - b
},
}
calculator.add(5, 3) // 8
calculator.subtract(5, 3) // 2
- Create an object
personwith propertiesfirstNameandlastName - Add a method
getFullNamethat returns the full name (firstName + lastName) - Add a method
greetthat returns "Hello, I'm [fullName]!" - Call both methods and log the results
💰 Inside a method, use
this to refer to the object itself:const person = {
name: 'Alice',
sayHi() {
return 'Hi, I am ' + this.name
},
}