JavaScript Object Methods

Object methods are functions stored as properties, giving objects behavior. They can also reference this to operate on the object’s own data.

Key Topics

Defining Methods

Define methods in object literals, classes, or via prototype assignment. Methods add behavior to objects.

let car = {
    brand: "Ford",
    drive() {
        console.log("Driving " + this.brand);
    }
};
car.drive();

Output

> Driving Ford

Explanation: The drive method references this.brand, allowing each car instance to use its own brand.

Using this

Within an object method, this refers to the object, letting you access or modify its properties. In arrow functions, this is inherited from the parent scope instead.

Object.keys(), Object.values(), Object.entries()

These methods let you iterate over object properties and values programmatically, useful for building dynamic logic or UI.

JavaScript Usage in DOM

Group DOM manipulation or event logic into object methods. This approach keeps your code organized, especially for larger UI components.

<!DOCTYPE html>
<html>
<head><title>Object Methods in DOM</title></head>
<body>
    <h1>Object Methods Demo</h1>
    <button onclick="app.showGreeting()">Greet</button>
    <p id="display"></p>

    <script>
        let app = {
            greeting: "Hello World",
            showGreeting() {
                document.getElementById("display").textContent = this.greeting;
            }
        };
    </script>
</body>
</html>

Key Takeaways

  • Methods: Functions as properties, enabling object behavior.
  • this Context: Points to the object, storing or updating its data.
  • Object Iteration: Object.keys(), Object.values() for dynamic usage.
  • DOM Integration: Methods can handle UI logic and interactions seamlessly.