JavaScript的Object详解

发布于:2025-07-19 ⋅ 阅读:(19) ⋅ 点赞:(0)

本文详细介绍JavaScript的Object核心概念和使用方法。

1. 对象基础
// 创建对象的两种方式
const person = {
  name: "obj",
  age: 30,
  greet: function() {
    return `Hello, ${this.name}`;
  }
};

// 或使用构造函数
const anotherPerson = new Object();
anotherPerson.name = "Bob";
anotherPerson["age"] = 25;
anotherPerson.greet = function() {
  return `Hi, ${this.name}`;
};
2. 对象属性操作
// 访问属性
console.log(person.name); // "obj"
console.log(person["age"]); // 30

// 修改属性
person.age = 31;

// 添加新属性
person.city = "New York";

// 删除属性
delete person.age;

// 检查属性是否存在
console.log("name" in person); // true
console.log(person.hasOwnProperty("name")); // true (不检查原型链)
3. 对象方法
// 对象方法的简写(ES6+)
const calculator = {
  value: 0,
  add(a) {
    this.value += a;
    return this; // 支持链式调用
  },
  subtract(a) {
    this.value -= a;
    return this;
  }
};

calculator.add(5).subtract(2);
console.log(calculator.value); // 3
4. 对象迭代
const person = { name: "obj", age: 30, city: "New York" };

// 遍历所有可枚举属性(包括对象自身和原型链上的)
for (const key in person) {
  console.log(key, person[key]);
}

// 只遍历对象自身的属性
Object.keys(person).forEach(key => {
  console.log(key, person[key]);
});

// 获取键值对数组
const entries = Object.entries(person);
console.log(entries); // [["name", "obj"], ["age", 30], ["city", "New York"]]
5. 对象复制与合并
// 浅复制
const shallowCopy = { ...person }; // 展开语法(ES6+)
const anotherCopy = Object.assign({}, person); // 等价于上面

// 深复制(简单实现,不处理函数、正则等特殊对象)
function deepCopy(obj) {
  return JSON.parse(JSON.stringify(obj));
}

// 合并多个对象
const target = { a: 1 };
const source1 = { b: 2 };
const source2 = { c: 3 };
const merged = Object.assign(target, source1, source2);
console.log(merged); // { a: 1, b: 2, c: 3 }
6. 对象与 JSON
// 对象转 JSON 字符串
const json = JSON.stringify(person);
console.log(json); // '{"name":"obj","age":30,"city":"New York"}'

// JSON 字符串转对象
const parsed = JSON.parse(json);
console.log(parsed.name); // "obj"
7. 对象的原型

每个对象都有一个原型对象,继承其属性和方法:

// 创建原型对象
const animal = {
  speak() {
    console.log(`${this.name} makes a sound.`);
  }
};

// 创建新对象并设置原型
const dog = Object.create(animal);
dog.name = "Buddy";
dog.speak(); // "Buddy makes a sound."

// 检查原型关系
console.log(Object.getPrototypeOf(dog) === animal); // true
8. 冻结与密封对象
// 冻结对象(不可添加、删除、修改属性)
const frozen = Object.freeze({ key: "value" });
frozen.key = "new"; // 无效操作(严格模式下报错)

// 密封对象(不可添加、删除属性,但可修改现有属性)
const sealed = Object.seal({ key: "value" });
sealed.key = "new"; // 允许
sealed.newKey = "test"; // 无效
9. 对象属性描述符

使用 Object.defineProperty() 精确控制属性行为:

const person = {};
Object.defineProperty(person, "name", {
  value: "obj",
  writable: false, // 不可修改
  enumerable: true, // 可枚举(出现在for-in循环中)
  configurable: false // 不可删除或重新定义
});

person.name = "Bob"; // 无效(严格模式下报错)
delete person.name; // 无效
10. 对象的应用场景
// 1. 配置对象
function initialize(options) {
  const config = {
    host: "localhost",
    port: 3000,
    ...options // 合并用户配置
  };
  // 使用配置...
}

// 2. 字典(Map)
const translations = {
  hello: "Bonjour",
  goodbye: "Au revoir"
};

// 3. 命名空间
const Utils = {
  calculate(a, b) {
    return a + b;
  },
  formatDate(date) {
    return date.toISOString();
  }
};



← 上一篇 AngularJS知识快速入门(上)
记得点赞、关注、收藏哦!
下一篇 Ajax——在OA系统提升性能的局部刷新 →

网站公告

今日签到

点亮在社区的每一天
去签到