Object methods are functions that are defined as properties of an object. They allow us to perform actions or calculations using the object's properties or other data.
In JavaScript, object methods are defined by assigning a function to a property of the object. The function can then be called using dot notation and parentheses.
For example, let's say we have an object person with properties name and age. We can define a method called greet that logs a greeting message using the person's name:
1const person = {
2 name: 'John',
3 age: 25,
4 greet: function() {
5 console.log('Hello, my name is ' + this.name);
6 }
7};
8
9person.greet();In this example, the greet method is defined as a function that logs a greeting message using the name property of the person object.
When calling a method, the this keyword refers to the object itself. In the greet method, this.name refers to the name property of the person object.
You can define multiple methods for an object, each performing different actions or calculations. Methods can also accept parameters and return values, just like regular functions.
Try running the code example to see the output.
xxxxxxxxxx// In JavaScript, objects can have methods, which are functions that are defined as properties of the object.// For example, let's say we have an object called `person` with properties `name` and `age`. We can define a method called `greet` that logs a greeting message using the person's name.const person = { name: 'John', age: 25, greet: function() { console.log('Hello, my name is ' + this.name); }};// To call the method, we can use dot notation and parentheses:person.greet();// Output: Hello, my name is John

