Object methods in JavaScript are functions associated with objects. They allow objects to encapsulate behavior and provide a way to perform actions related to the object's data.
Methods can be added to objects during object creation or afterward.
1. Object Literal
let person = {
firstName: "John",
lastName: "Doe",
fullName: function() {
return this.firstName + " " + this.lastName;
}
};
function Person(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
this.fullName = function() {
return this.firstName + " " + this.lastName;
};
}
let person = new Person("John", "Doe");
Object methods are invoked using dot notation.
function Person(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
this.fullName = function() {
return this.firstName + " " + this.lastName;
};
}
let person = new Person("John", "Doe");
let fullName = person.fullName();
console.log(fullName); // John Doe
Inside an object method, the this keyword refers to the object that the method belongs to. It allows you to access the object's properties and other methods.
let person = {
firstName: "John",
lastName: "Doe",
greet: function() {
console.log("Hello, " + this.firstName + "!");
}
};
person.greet(); // Outputs: Hello, John!
Arrow functions don't have their own this. They inherit this from the surrounding scope.
let person = {
firstName: "John",
sayHello: () => {
console.log("Hello, " + this.firstName + "!"); // 'this' is undefined
}
};
person.sayHello(); // Outputs: Hello, undefined!
Methods can also be added to an object's prototype, making them available to all instances of the object.
function Person(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
Person.prototype.fullName = function() {
return this.firstName + " " + this.lastName;
};
// Create instances of Person
const person1 = new Person("John", "Doe");
const person2 = new Person("Jane", "Smith");
// Call the fullName method on the instances
console.log(person1.fullName()); // Output: "John Doe"
console.log(person2.fullName()); // Output: "Jane Smith"
Object methods allow objects to encapsulate behavior, making them more than just data containers. They enable objects to perform actions and provide functionality.