Home JavaScript Tutorial Javascript Object Methods

Javascript Object Methods

by Anup Maurya
27 minutes read

In this tutorial, you’ll learn about JavaScript object methods and how to define methods for an object.

Introduction to the JavaScript object methods

An object is a collection of key/value pairs or properties. When the value is a function, the property becomes a method. Typically, you use methods to describe the object’s behaviors.

For example, the following adds the greet method to the person object:

let person={
  firstname:"Anup",
  lastname:"Maurya"
}

person.greet = function () {
    console.log('Welcome to India!');
}

person.greet();

Output:

Welcome to India!

In this example:

  • First, use a function expression to define a function and assign it to the greet property of the person object.
  • Then, call the method greet() method.

Besides using a function expression, you can define a function and assign it to an object like this:

In this example:

  • First, define the greet() function as a regular function.
  • Second, assign the function name to the greet property of the person object.
  • Third, call the greet() method.

Object method shorthand

JavaScript allows you to define methods of an object using the object literal syntax as shown in the following example:

let person = {
    
  firstname:"Anup",
  lastname:"Maurya",
    greet: function () {
         console.log('Welcome to India!');
    }
};

ES6 provides you with the concise method syntax that allows you to define a method for an object:

const person ={
   firstname:"Anup",
   lastname:"Maurya",
   greet(){
       console.log("Welcome to India!")
   }
}

This syntax looks much cleaner and less concise.

What is this in JavaScript?

In JavaScript, the this keyword refers to an object.

const person = {
  firstName: "Anup",
  lastName: "Maurya",
  id: 5566,
  fullName: function() {
    return this.firstName + " " + this.lastName;
  }
};

Which object depends on how this is being invoked (used or called).

The this keyword refers to different objects depending on how it is used:

In an object method, this refers to the object.
Alone, this refers to the global object.
In a function, this refers to the global object.
In a function, in strict mode, this is undefined.
In an event, this refers to the element that received the event.
Methods like call()apply(), and bind() can refer this to any object.

related posts

Leave a Comment

Enable Notifications OK No thanks