Home Courses Object Methods in JavaScript - this Keyword & Method Calling

Object Methods in JavaScript - this Keyword & Method Calling

What is an Object Method?

  1. An object method is a function inside an object
  2. It is used to perform actions using object data

Example:


let userDetails = {
name: "Anil",
greet: function () {
return "Hello";
}
}

  1. greet is a method (function inside object)


How to Create a Method


greet: function () {
return "Hello User";
}

  1. Method is created like a property
  2. Value is a function


How to Call a Method


userDetails.greet()

  1. Use () to execute the function
  2. Without () it will not run


Using Object Properties Inside Method (this keyword)


greet: function () {
return "Hello " + this.name;
}

  1. this refers to the current object
  2. this.name accesses 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;
}

  1. 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

  1. Methods are functions inside objects
  2. Use this to access object properties
  3. Use () to call methods
  4. Methods can take parameters
  5. Methods can call other methods


Share this lesson: