JavaScript Object Methods



What is this?

In JavaScript, when we use the this keyword, it points to an object.

Which object's dependence is determined by the way this is utilized or called.

The word "this" means different things based on how it's used:

In a method related to an object, the term this points to the actual object.
By itself, the term this points to the overall object, which is known as the global object.
In a function, the keyword "this" points to the overall object, which is known as theglobal object.
In a function under strict mode, the value ofthis is undefined.
During an occurrence, the term this indicates the specific element that got the event.
Functions such as call(), apply(), andbind() can associate the keyword this with any object.

Note

this is not like a variable; it's a keyword. You can't alter the value of this.


JavaScript Methods

JavaScript methods are like tasks you can do with objects.

A JavaScript method is like a container that holds a specific function definition.

Property Value
firstName John
lastName Doe
age 50
eyeColor blue
fullName function() {return this.firstName + " " + this.lastName;}

Methods are like tools saved as part of an object.


Accessing Object Methods

To use an object method, you can follow this syntax:

objectName.methodName()

Usually, you explain fullName() as an action related to the person object, and fullName as something that belongs to it.

The fullName property works like a function. It gets executed when you use () to invoke it.

This sample demonstrates how to use the fullName() method of a person object.

If you use the fullName property without (), it will display thefunction definition:


Adding a Method to an Object

Creating a new method for an object is simple:


Using Built-In Methods

This example employs the toUpperCase() method of the String object to change text to uppercase.

let message = "Hello world!";
let x = message.toUpperCase();

After running the provided code, the result for the variable "x" will be:

HELLO WORLD!