Js Object Methods in JavaScript
? JavaScript Object Methods
In JavaScript, object methods are functions stored as object properties. They allow objects to perform actions using their own data.
? What Is a Method?
A method is just a function inside an object.
let person = { firstName: "Alice", lastName: "Johnson", fullName: function () { return this.firstName + " " + this.lastName; }};console.log(person.fullName()); // "Alice Johnson"?
thisrefers to the object the method belongs to (personin this case).
?? Defining Object Methods
? Regular Function
let car = { brand: "Toyota", model: "Corolla", start: function () { return this.brand + " " + this.model + " started!"; }};? ES6 Shorthand
let car = { brand: "Toyota", model: "Corolla", start() { return `${this.brand} ${this.model} started!`; }};? Reusable Methods Using Constructor
function Person(name) { this.name = name; this.sayHello = function () { return "Hi, I'm " + this.name; };}let p1 = new Person("Bob");console.log(p1.sayHello()); // Hi, I'm Bob? Common Built-in Object Methods
| Method | Description |
|---|---|
Object.keys(obj) | Returns array of keys |
Object.values(obj) | Returns array of values |
Object.entries(obj) | Returns array of [key, value] pairs |
Object.assign(target, source) | Copies values from source to target |
Object.hasOwnProperty(key) | Checks if key exists on object |
? Example
let user = { name: "Eve", age: 30};console.log(Object.keys(user)); // ["name", "age"]console.log(Object.values(user)); // ["Eve", 30]console.log(Object.entries(user)); // [["name", "Eve"], ["age", 30]]? Arrow Functions as Methods (?? Avoid)
Avoid arrow functions when using this in object methods:
let obj = { name: "Test", greet: () => { console.log(this.name); // ? 'this' is not bound to obj }};Use regular functions or shorthand method syntax instead.
? Summary
Object methods = functions inside objects
Use
thisto access object propertiesPrefer regular functions or method shorthand (not arrow functions)
Use built-in methods like
Object.keys(),Object.assign(), etc.
Would you like to learn how to dynamically add or remove methods from objects?