A method is a function stored as a property of an object. Properties describe what an object is; methods describe what it can do.
const dog = {
name: "Rex",
bark: function() {
return "Woof!";
}
};
console.log(dog.bark());
Modern JavaScript lets you leave out the colon and the word function. This is the style you will see most:
const dog = {
name: "Rex",
bark() {
return "Woof!";
}
};
console.log(dog.bark()); // "Woof!" (calls the method)
console.log(dog.bark); // the function itself, not its result
const calculator = {
add(a, b) { return a + b; },
subtract(a, b) { return a - b; },
average(...nums) {
let sum = 0;
for (const n of nums) sum += n;
return sum / nums.length;
}
};
console.log(calculator.add(4, 5));
console.log(calculator.average(80, 90, 100));
Grouping related functions inside one object keeps them organized. This is exactly what the built-in Math object does with Math.round, Math.max, and the rest.
The real power of methods is working with the object's own properties. The keyword this means "the object this method was called on":
const account = {
owner: "Jordan",
balance: 100,
deposit(amount) {
this.balance += amount;
return this.balance;
},
summary() {
return `${this.owner} has $${this.balance}`;
}
};
account.deposit(50);
console.log(account.summary());
this is important enough, and tricky enough, to get its own lesson next. For now: inside a method, this.balance means "this object's balance."
Methods are just properties, so you can add one after the object is created:
const robot = { name: "Unit 7" };
robot.introduce = function() {
return `I am ${this.name}`;
};
console.log(robot.introduce());
Arrow functions do not get their own this, so they cannot see the object:
const cat = {
sound: "meow",
speakGood() { return this.sound; },
speakBad: () => this.sound
};
console.log(cat.speakGood()); // "meow"
console.log(cat.speakBad()); // undefined
name() { } syntax for methods. Save arrow functions for callbacks inside methods.
"hello".toUpperCase() // string method
(3.14159).toFixed(2) // number method
Math.random() // Math object method
console.log() // console object method
Object.keys(obj) // Object helper method
What does this log?
const light = {
on: false,
toggle() { this.on = !this.on; }
};
light.toggle();
light.toggle();
light.toggle();
console.log(light.on);
true. Each call flips on: false to true, true to false, false to true.What does dog.bark (no parentheses) give you?
undefined() you get the method, not its result. Same rule as any function.Why does speakBad: () => this.sound return undefined?
this, so it is not the objectfunctionsound is misspelledthis of the code around the object, not the object itself. Use the speakGood() { } shorthand for methods.lamp turnOn() and turnOff() methodsstatus() method that returns "Lamp is on" or "Lamp is off" using thiscToF(c) and fToC(f) methodsthis