HTML CSS Bootstrap JavaScript jQuery MySQL PHP Data Mining

JavaScript Object Methods

Objects are not just for storing values; they can also contain behaviors. In JavaScript, a method is a function stored as an object property. Methods allow objects to "do" things, often using their own data.


Defining a Method

A method is defined just like a regular property, but with a function as its value.

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

Accessing Object Methods

You can access an object method using the dot notation, followed by parentheses () to execute (call) the method.

let name = person.fullName();
console.log(name); // "Mim Akter"
Warning: If you access a method without parentheses, it will return the function definition itself, not the result of the function.

The 'this' Keyword

In JavaScript, the this keyword refers to an object. Which object depends on how this is being invoked.

In an object method, this refers to the object that "owns" the method. In the example above, this refers to the person object.


Adding a Method Dynamically

Just like properties, you can add a method to an object after it has been created.

const person = {
  firstName: "Mim",
  lastName: "Akter"
};

person.greet = function() {
  return "Hello, my name is " + this.firstName;
};

console.log(person.greet()); // "Hello, my name is Mim"

Using Built-in Methods

You can use standard JavaScript functions inside your methods. For example, converting text to uppercase:

const person = {
  firstName: "Mim",
  lastName: "Akter",
  shoutName: function() {
    return (this.firstName + " " + this.lastName).toUpperCase();
  }
};

Key Points to Remember

  • A method is a function definition stored as a property
  • Always use parentheses () to execute a method
  • The this keyword allows methods to access their own object's properties
  • Methods keep your code organized by grouping data and logic together
  • Methods can be added to objects dynamically at any time