DEV Community

Cover image for JavaScript Methods and this Keyword
Manikandan K
Manikandan K

Posted on

JavaScript Methods and this Keyword

OBJECT METHODS

  • JavaScript Object contains a function as a value in a key/name.
  • Simply, JavaScript Method is an Object property that has a function.

Syntax

const object_name = {
    key_1: value_1;
    key_2: value_2
    key_3: function() {
        // code to be execute.
    }   
}
Enter fullscreen mode Exit fullscreen mode

Accessing Methods
We know how to access an object and how to call a function. Both will combine we can access the JavaScript method.

Syntax

objectName.key(or)method name();
Enter fullscreen mode Exit fullscreen mode

NOTE :
To access the methods, we put must () end of the method name.

Example

const person = {
  name: 'Manikandan',
  age: 24,
  sayHello: function () {
    console.log('Hello Manikandan');
  },
};

// ** access property
console.log(person.name); // Manikandan

// ** access property as well as function in an object.
console.log(person.sayHello); // [Function: sayHello]

// ** access method
person.sayHello(); // Hello Manikandan

Enter fullscreen mode Exit fullscreen mode

Image description

'this' key word

To access a property of an object from within a method of the same object,
we use this keyword.

const person = {
    name: 'Manikandan',
    age: 23,
    sayHello: function() {
        console.log(`Hi, This is ${this.name}. I am ${this.age} yrs old`);
    }
}

person.sayHello();
Enter fullscreen mode Exit fullscreen mode

here,
sayHello method(person.sayHello) needs to access name property in same object(person.name).
Both of the same Object.(person) so we used this keyword here.

Image description

Top comments (0)