JavaScript Object Methods

In JavaScript, an object can also contain a function. For example,

const person = {

    name: "Sam",

    age: 30,

    // using function as a value

    greet: function() { console.log('hello') }

}

person.greet(); // hello

Here, a function is used as a value for the greet key. That's why we need to use person.greet() instead of person.greet to call the function inside the object.

A JavaScript method is a property containing a function declaration.

EXAMPLE ❯


The this Keyword

In a function definition, this refers to the "owner" of the function.

In the example above, this is the person object that "owns" the fullName function.

In other words, this.firstName means the firstName property of this object.


JavaScript Methods

JavaScript methods are actions that can be performed on objects.

Methods are functions stored as object properties.


Accessing Object Methods

You access an object method with the following data

Syntax:

objectName.methodName()

You will typically describe fullName() as a method of the person object, and fullName as a property.

The fullName property will execute (as a function) when it is invoked with ().

This example accesses the fullName() method of a person object

Example:

name = person.fullName();

If you access the fullName property, without (), it will return the function definition:

EXAMPLE ❯


Adding a Method to an Object

Adding a new method to an object is easy:

EXAMPLE ❯


Using Built-In Methods

This example uses the toUpperCase() method of the String object, to convert a text to uppercase:

let message = "Hello world!";

let x = message.toUpperCase();

EXAMPLE ❯