JavaScript Object Methods & this Keyword Explained
What is an Object Method?
An object method is a function stored inside an object. It allows the object to perform actions using its own data.
1. Defining Object Methods
Example:
let person = {
firstName: "Alice",
lastName: "Smith",
fullName: function () {
return this.firstName + " " + this.lastName;
}
};
console.log(person.fullName());
Output
Alice Smith
this refers to the object (person) that owns the method.
2. The this Keyword in Object Methods
Example:
let car = {
brand: "Tesla",
model: "Model 3",
showInfo: function () {
console.log("Car: " + this.brand + " " + this.model);
}
};
car.showInfo();
Output
Car: Tesla Model 3
this.brand refers to car.brand.
3. Arrow Functions and this Inside Objects
Arrow functions do not have their own this — they inherit this from the outer scope.
Example:
let user = {
name: "John",
sayHi: () => {
console.log("Hi " + this.name);
}
};
user.sayHi();
Output
Hi undefined
Use regular functions (not arrow functions) for methods to access this correctly.
4. Shorthand Method Syntax (ES6)
You can define object methods more cleanly using shorthand.
Example:
let dog = {
name: "Buddy",
bark() {
return this.name + " says woof!";
}
};
console.log(dog.bark());
Output
Buddy says woof!
5. Method Reuse with this
You can reuse methods across multiple objects using this.
Example:
function greet() {
console.log("Hello, I am " + this.name);
}
let user1 = { name: "Ava", greet: greet };
let user2 = { name: "Liam", greet: greet };
user1.greet(); // Hello, I am Ava
user2.greet(); // Hello, I am Liam
Summary Table – Object Methods & this
Concept | Description | Example Syntax |
---|---|---|
Object Method | Function inside an object | obj.method = function() {} |
this Keyword | Refers to the object calling the method | this.propertyName |
Arrow Function in Method | Inherits this from outer scope (avoid) | sayHi: () => {} |
Shorthand Syntax | ES6 clean method definition | method() {} |