Object Methods
Objects can hold functions, called methods.
Syntax
let obj = { method() { ... } };A property whose value is a function is called a method. Methods let objects perform actions.
Defining a method
Use the shorthand greet() { ... } inside the object. Call it with obj.greet().
Example
Loading editor…
Press Run to execute the code.
When to use it
- Attach a calculateTotal method to an order object so the logic stays close to its data.
- Clone a config object with Object.assign to avoid mutating the original when overriding defaults.
- Merge multiple partial config objects into one with the spread operator before passing to a function.
More examples
Method defined on an object
Defines a getTotal method on an object using shorthand syntax, accessing sibling data via this.
const order = {
items: [{ price: 10 }, { price: 25 }],
getTotal() {
return this.items.reduce((sum, item) => sum + item.price, 0);
}
};
console.log(order.getTotal()); // 35Object.assign to merge
Uses Object.assign to create a new object by merging defaults with user-provided overrides.
const defaults = { timeout: 3000, retries: 3 };
const overrides = { retries: 5, debug: true };
const config = Object.assign({}, defaults, overrides);
console.log(config); // { timeout: 3000, retries: 5, debug: true }Object.freeze to lock an object
Applies Object.freeze to prevent any property of a constants object from being modified at runtime.
const STATUS = Object.freeze({ PENDING: 0, ACTIVE: 1, CLOSED: 2 });
// STATUS.PENDING = 99; // silently ignored in sloppy mode
console.log(STATUS.ACTIVE); // 1
Discussion