Object Methods in JavaScript - this Keyword & Method Calling
What is an Object Method?
- An object method is a function inside an object
- It is used to perform actions using object data
Example:
let userDetails = {
name: "Anil",
greet: function () {
return "Hello";
}
}
greetis a method (function inside object)
How to Create a Method
greet: function () {
return "Hello User";
}
- Method is created like a property
- Value is a function
How to Call a Method
userDetails.greet()
- Use
()to execute the function - Without
()it will not run
Using Object Properties Inside Method (this keyword)
greet: function () {
return "Hello " + this.name;
}
thisrefers to the current objectthis.nameaccesses object property
Example
let userDetails = {
name: "Anil",
greet: function () {
return "Hello " + this.name;
}
}
Output:
userDetails.greet() // Hello Anil
Method with Parameters
hello: function (from) {
return "Hello " + this.name + ", this is " + from;
}
Call:
userDetails.hello("Peter")
Calling One Method Inside Another
hello: function (from) {
return this.greet() + " this is " + from;
}
this.greet()calls another method of same object
Full Example
let userDetails = {
name: "Anil sidhu",
greet: function () {
return "Hello " + this.name + ", How are you";
},
hello: function (from) {
return this.greet() + " this is " + from;
}
}
console.log(userDetails.hello("peter"));
Output:
Hello Anil sidhu, How are you this is peter
Important Concepts to Remember
- Methods are functions inside objects
- Use
thisto access object properties - Use
()to call methods - Methods can take parameters
- Methods can call other methods