JavaScript Object Methods

Object methods are functions stored as properties inside an object. They allow objects to have behaviors, making them more dynamic and interactive.

Key Topics

Defining Methods

Methods are functions assigned to object properties, enabling objects to perform actions related to their data.

let person = {
    name: "Alice",
    greet: function() {
        console.log("Hello, " + this.name);
    }
};
person.greet();

Output

> Hello, Alice

Explanation: The greet method uses the this keyword to access the person object's name property, printing a personalized greeting.

Using the this Keyword

The this keyword refers to the current object in which the method is defined, allowing methods to access other properties and methods within the same object.

let car = {
    brand: "Toyota",
    model: "Camry",
    getInfo: function() {
        return this.brand + " " + this.model;
    }
};
console.log(car.getInfo());

Output

> Toyota Camry

Explanation: The this keyword inside getInfo refers to the car object, accessing its brand and model properties to construct a descriptive string.

Calling Object Methods

Object methods are called using dot notation. The method executes its function body and may return a value.

let mathOps = {
    add: function(a, b) {
        return a + b;
    }
};
let result = mathOps.add(2, 3);
console.log("Result: ", result);

Output

> Result: 5

Explanation: The add method is called with arguments 2 and 3, returning their sum and logging it to the console.

JavaScript Usage in DOM

This DOM-based example demonstrates an object with a method used to update page content dynamically.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Object Methods in DOM</title>
</head>
<body>
    <h1>Object Methods Demo</h1>
    <button onclick="showInfo()">Show Info</button>
    <p id="info"></p>

    <script>
        let user = {
            name: "Charlie",
            role: "Designer",
            getDetails: function() {
                return this.name + " is a " + this.role;
            }
        };
        function showInfo() {
            document.getElementById("info").textContent = user.getDetails();
        }
    </script>
</body>
</html>

Key Takeaways

  • Method Definition: Functions as properties add functionality to objects.
  • this Keyword: Provides access to the object's own data within methods.
  • Calling Methods: Invoke methods using dot notation and arguments.
  • DOM Integration: Use methods to dynamically update webpage content.