Objects are not just for storing values; they can also contain behaviors. In JavaScript, a method is a function stored as an object property. Methods allow objects to "do" things, often using their own data.
A method is defined just like a regular property, but with a function as its value.
const person = {
firstName: "Mim",
lastName: "Akter",
id: 5566,
fullName: function() {
return this.firstName + " " + this.lastName;
}
};
You can access an object method using the dot notation, followed by
parentheses () to execute (call) the method.
let name = person.fullName();
console.log(name); // "Mim Akter"
In JavaScript, the this keyword refers to an object. Which
object depends on how this is being invoked.
In an object method, this refers to the object that "owns" the
method. In the example above, this refers to the
person object.
Just like properties, you can add a method to an object after it has been created.
const person = {
firstName: "Mim",
lastName: "Akter"
};
person.greet = function() {
return "Hello, my name is " + this.firstName;
};
console.log(person.greet()); // "Hello, my name is Mim"
You can use standard JavaScript functions inside your methods. For example, converting text to uppercase:
const person = {
firstName: "Mim",
lastName: "Akter",
shoutName: function() {
return (this.firstName + " " + this.lastName).toUpperCase();
}
};
() to execute a methodthis keyword allows methods to access their own object's properties