Object Methods in JavaScript
Object Methods in JavaScript
What Are Object Methods?
Methods are functions that are stored as properties inside objects.
They define behavior or actions that an object can perform.
Defining Methods in Objects
1. Using Function Expressions
const person = { name: "Alice", greet: function() { console.log("Hello, " + this.name); }};person.greet(); // Output: Hello, Alice2. Using ES6 Shorthand Method Syntax
const person = { name: "Alice", greet() { console.log("Hello, " + this.name); }};person.greet(); // Output: Hello, AliceUsing this Keyword
Inside a method,
thisrefers to the object that called the method.
const car = { brand: "Toyota", showBrand() { console.log("Brand: " + this.brand); }};car.showBrand(); // Brand: ToyotaExample with Parameters
const calculator = { add(a, b) { return a + b; }, multiply(a, b) { return a * b; }};console.log(calculator.add(2, 3)); // 5console.log(calculator.multiply(4, 5)); // 20Summary
| Concept | Explanation |
|---|---|
| Method | Function inside an object |
| Shorthand Syntax | Easier syntax for methods |
this | Refers to current object |
| Parameters | Methods can accept arguments |
Would you like examples of advanced methods or object prototypes?