JavaScript Object Definitions

An object in JavaScript is a collection of key-value pairs. Each key can be a string or symbol, and its value can be any data type. Objects let you group related data and functionality together.

Key Topics

Object Literals

Object literals are the most common way to create objects using curly braces and key-value pairs.

let person = {
    name: "Alice",
    age: 25
};
console.log(person.name);

Output

> Alice

Explanation: The person object has two properties, name and age. We access name via dot notation.

Constructor Functions

Constructor functions use the new keyword to create object instances with shared structure. Properties and methods are defined on this within the constructor.

function Person(name, age) {
    this.name = name;
    this.age = age;
}
let p = new Person("Bob", 30);
console.log(p.age);

Output

> 30

Explanation: Creating a new Person object assigns name and age properties to this in the constructor.

Class Syntax

ES6 introduced class syntax, a cleaner way to define constructor functions and methods.

class Car {
    constructor(brand) {
        this.brand = brand;
    }
    drive() {
        console.log("Driving a " + this.brand);
    }
}
let c = new Car("Toyota");
c.drive();

Output

> Driving a Toyota

Explanation: The Car class provides a constructor and a method drive. Instances inherit these members automatically.

JavaScript Usage in DOM

Use object definitions to store and manipulate DOM-related data. For instance, an object can hold references to multiple DOM elements, organizing logic for complex user interfaces.

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Object Definitions in DOM</title>
</head>
<body>
    <h1>Object Definitions Demo</h1>
    <button onclick="ui.displayMessage()">Show Message</button>
    <p id="info"></p>

    <script>
        let ui = {
            element: document.getElementById("info"),
            displayMessage() {
                this.element.textContent = "Hello from our UI object!";
            }
        };
    </script>
</body>
</html>

Key Takeaways

  • Object Literals: Easiest way to create single objects.
  • Constructors/Classes: Ideal for multiple similar objects.
  • DOM Integration: Store references, manipulate elements logically.