DEV Community

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

Posted on

4 3

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

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (0)

SurveyJS custom survey software

JavaScript Form Builder UI Component

Generate dynamic JSON-driven forms directly in your JavaScript app (Angular, React, Vue.js, jQuery) with a fully customizable drag-and-drop form builder. Easily integrate with any backend system and retain full ownership over your data, with no user or form submission limits.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay