404 Not Found

404 Not Found


nginx

JavaScript Objects

Objects are the most essential data structure in JavaScript. Think of them as info cards — the front says "Name: Alice" and the back says "Age: 20". Each piece of information has a key and a value, forming a key-value pair.

📖 Summary

Creating Object Literals

Use curly braces {} to write an object directly — this is the most common approach:

HTML
<script>
const student = {
  name: "Alice",
  age: 20,
  major: "Computer Science"
};
console.log(student);
</script>

Key-value pairs are separated by colons, and pairs are separated by commas. A trailing comma after the last pair is allowed (and convenient for future additions).

Accessing Properties

Two ways to access object properties:

Method Syntax When to Use
Dot notation obj.name When the property name is a valid identifier
Bracket notation obj["name"] When the name contains special characters or is stored in a variable

Bracket notation's biggest advantage: you can use a variable as the key.

HTML
<script>
const key = "name";
console.log(student[key]); // Same as student["name"]
</script>

Modifying and Adding Properties

After creating an object, you can modify existing properties or add new ones at any time — even if the object was declared with const (const locks the reference, not the content).

HTML
<script>
student.age = 21;          // Modify
student.grade = "Junior";  // Add new property
console.log(student);
</script>

Deleting Properties

Use the delete operator to remove a property entirely:

HTML
<script>
delete student.grade;
console.log(student);
</script>

After deletion, accessing that property returns undefined.

Methods

A function inside an object is called a method. When a function becomes a property value, the object can "do things":

HTML
<script>
const dog = {
  name: "Rex",
  bark() {
    return "Woof! I'm " + this.name;
  }
};
console.log(dog.bark());
</script>

The this Keyword

this refers to "the current object" — whoever calls the method, this is that object. This is one of JavaScript's trickiest concepts: if a method is extracted and called separately, this no longer points to the original object.

HTML
<script>
const bark = dog.bark;
console.log(bark()); // this no longer points to dog — may be window or undefined
</script>

Constructors

When you need to批量创建 multiple objects with the same structure, use a constructor function:

HTML
<script>
function Person(name, age) {
  this.name = name;
  this.age = age;
  this.sayHi = function() {
    return "Hi, I'm " + this.name;
  };
}

const p1 = new Person("Bob", 25);
const p2 = new Person("Charlie", 30);
console.log(p1.sayHi());
console.log(p2.sayHi());
</script>

new does three things: creates an empty object → sets this to point to it → returns the object.

Object.keys / values / entries

These three static methods return arrays of an object's keys, values, and key-value pairs:

Method Returns
Object.keys(obj) ["name", "age"]
Object.values(obj) ["Alice", 20]
Object.entries(obj) [["name","Alice"], ["age",20]]

Very useful for iterating over objects: Object.keys(obj).forEach(key => ...).


Example: Creating a Student Object and Displaying Info

HTML
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Object Basics</title>
  <style>
    body { font-family: sans-serif; padding: 20px; }
    .card { border: 2px solid #4a90d9; border-radius: 8px; padding: 16px; max-width: 360px; background: #f0f7ff; }
    .card h3 { margin: 0 0 8px; color: #4a90d9; }
    .card p { margin: 4px 0; }
  </style>
</head>
<body>
  <h2>Student Info Card</h2>
  <div id="output"></div>
  <script>
    const student = {
      name: "Alice",
      age: 20,
      major: "Computer Science",
      gpa: 3.7,
      introduce() {
        return `My name is ${this.name}, I'm ${this.age} years old, majoring in ${this.major} with a GPA of ${this.gpa}.`;
      }
    };

    const output = document.getElementById("output");
    output.innerHTML = `
      <div class="card">
        <h3>${student.name}</h3>
        <p>Age: ${student.age}</p>
        <p>Major: ${student.major}</p>
        <p>GPA: ${student.gpa}</p>
        <p><em>${student.introduce()}</em></p>
      </div>
    `;
  </script>
</body>
</html>
▶ Try it Yourself

Example: Dot Notation vs Bracket Notation

HTML
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Property Access Methods</title>
  <style>
    body { font-family: sans-serif; padding: 20px; }
    .result { background: #f5f5f5; padding: 12px; border-radius: 6px; margin: 8px 0; }
    code { background: #e0e0e0; padding: 2px 6px; border-radius: 3px; }
  </style>
</head>
<body>
  <h2>Property Access Comparison</h2>
  <div id="output"></div>
  <script>
    const user = {
      name: "Bob",
      age: 28,
      "home-city": "New York"
    };

    const key = "name";
    const results = [];

    results.push(`user.name → ${user.name}`);
    results.push(`user["name"] → ${user["name"]}`);
    results.push(`user[key](key="name") → ${user[key]}`);
    results.push(`user["home-city"] → ${user["home-city"]}`);

    document.getElementById("output").innerHTML = results
      .map(r => `<div class="result"><code>${r}</code></div>`)
      .join("");
  </script>
</body>
</html>
▶ Try it Yourself

Example: Dynamically Adding, Modifying, and Deleting Properties

HTML
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Working with Properties</title>
  <style>
    body { font-family: sans-serif; padding: 20px; }
    table { border-collapse: collapse; margin: 12px 0; }
    td, th { border: 1px solid #ccc; padding: 8px 14px; text-align: left; }
    th { background: #4a90d9; color: #fff; }
    .action { color: #888; font-style: italic; margin: 8px 0; }
  </style>
</head>
<body>
  <h2>Object Property Operations</h2>
  <div id="output"></div>
  <script>
    const product = { name: "Laptop", price: 999 };
    const log = [];

    function showState(label) {
      log.push({ label, snapshot: JSON.stringify(product) });
    }

    showState("Initial state");
    product.price = 899;
    showState("Changed price to 899");
    product.brand = "Lenovo";
    showState("Added brand property");
    delete product.brand;
    showState("Deleted brand property");

    const output = document.getElementById("output");
    output.innerHTML = "<table><tr><th>Action</th><th>Object State</th></tr>" +
      log.map(r => `<tr><td>${r.label}</td><td>${r.snapshot}</td></tr>`).join("") +
      "</table>";
  </script>
</body>
</html>
▶ Try it Yourself

Example: Constructors and Object.keys/values/entries

HTML
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Constructors & Object Methods</title>
  <style>
    body { font-family: sans-serif; padding: 20px; }
    .section { margin: 16px 0; padding: 12px; background: #f9f9f9; border-radius: 6px; }
    .section h3 { margin-top: 0; color: #4a90d9; }
    ul { padding-left: 20px; }
    li { margin: 4px 0; }
  </style>
</head>
<body>
  <h2>Constructors & Static Object Methods</h2>
  <div id="output"></div>
  <script>
    function Phone(brand, model, price) {
      this.brand = brand;
      this.model = model;
      this.price = price;
      this.showInfo = function() {
        return `${this.brand} ${this.model} — $${this.price}`;
      };
    }

    const p1 = new Phone("Samsung", "Galaxy S24", 899);
    const p2 = new Phone("Apple", "iPhone 15", 999);

    const keys = Object.keys(p1);
    const values = Object.values(p1);
    const entries = Object.entries(p1);

    document.getElementById("output").innerHTML = `
      <div class="section">
        <h3>Objects Created with Constructor</h3>
        <p>${p1.showInfo()}</p>
        <p>${p2.showInfo()}</p>
      </div>
      <div class="section">
        <h3>Object.keys(p1)</h3>
        <ul>${keys.map(k => `<li>${k}</li>`).join("")}</ul>
      </div>
      <div class="section">
        <h3>Object.values(p1)</h3>
        <ul>${values.map(v => `<li>${v}</li>`).join("")}</ul>
      </div>
      <div class="section">
        <h3>Object.entries(p1)</h3>
        <ul>${entries.map(([k, v]) => `<li><code>${k}</code>: <code>${v}</code></li>`).join("")}</ul>
      </div>
    `;
  </script>
</body>
</html>
▶ Try it Yourself

❓ FAQ

Q Can I modify properties of an object declared with const?
A Yes. const locks the variable's reference (meaning it always points to the same object), not the object's content. You can add, modify, and delete properties freely — but you can't reassign with obj = {}.
Q When should I use bracket notation instead of dot notation?
A When the property name contains spaces or hyphens (like "home-city"), or when the name is stored in a variable for dynamic access, you must use brackets. For everything else, dot notation is cleaner and preferred.
Q What happens if I forget new with a constructor?
A this will point to the global object (or undefined in strict mode), causing properties to land in the wrong place or throwing an error. This is a classic pitfall — ES6's class syntax handles this automatically.

📝 Exercises

  1. Create a book object with title, author, and year properties, plus a getSummary() method that returns a string like "title by author, published in year".
  2. Write a constructor Car(brand, model, year), use it to create 3 cars, then use Object.keys to list all property names of one car.
  3. Dynamically add a drive() method to any of the cars above (returns "brand model is driving"), then call it. Observe how this refers to the current object inside the method.
100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏