Skip to content

对象

什么是JavaScript对象?

JavaScript对象是一种复合数据类型,用于存储键值对的集合。对象是JavaScript中最重要和最基础的数据结构之一,几乎所有的JavaScript实体都是对象或可以转换为对象。


对象的基本概念

对象的定义

对象是由属性方法组成的无序集合,其中:

  • 属性:键值对,键通常是字符串(或Symbol),值可以是任何数据类型
  • 方法:值为函数的特殊属性

创建对象的方式

1
2
3
4
5
6
7
8
const person = {
  name: '张三',
  age: 25,
  city: '北京',
  greet: function() {
    return `你好,我是${this.name}`;
  }
};
function Person(name, age, city) {
  this.name = name;
  this.age = age;
  this.city = city;
  this.greet = function() {
    return `你好,我是${this.name}`;
  };
}

const person = new Person('李四', 30, '上海');
1
2
3
4
5
6
7
const person = new Object();
person.name = '王五';
person.age = 28;
person.city = '广州';
person.greet = function() {
  return `你好,我是${this.name}`;
};
1
2
3
4
5
6
7
8
9
const personPrototype = {
  greet: function() {
    return `你好,我是${this.name}`;
  }
};

const person = Object.create(personPrototype);
person.name = '赵六';
person.age = 32;

对象属性的操作

1
2
3
4
5
6
7
8
const obj = { name: 'test', 'full-name': 'full test' };

// 点符号访问
console.log(obj.name); // 'test'

// 方括号访问
console.log(obj['name']); // 'test'
console.log(obj['full-name']); // 'full test' - 只能用方括号访问带特殊字符的键
1
2
3
4
5
6
7
8
9
const obj = { name: 'test' };

// 添加新属性
obj.age = 25;
obj['city'] = '北京';

// 修改现有属性
obj.name = 'new name';
obj['age'] = 30;
1
2
3
4
const obj = { name: 'test', age: 25 };

delete obj.age; // 删除age属性
delete obj['name']; // 删除name属性

对象的遍历

1
2
3
4
5
6
7
const person = { name: '张三', age: 25, city: '北京' };

for (let key in person) {
  if (person.hasOwnProperty(key)) {
    console.log(key, person[key]);
  }
}
1
2
3
4
5
const person = { name: '张三', age: 25, city: '北京' };

Object.keys(person).forEach(key => {
  console.log(key, person[key]);
});
1
2
3
4
5
const person = { name: '张三', age: 25, city: '北京' };

Object.entries(person).forEach(([key, value]) => {
  console.log(key, value);
});

对象方法

const obj1 = { a: 1, b: 2 };
const obj2 = { c: 3, d: 4 };
const merged = Object.assign({}, obj1, obj2); // { a: 1, b: 2, c: 3, d: 4 }
const obj = { name: 'test', age: 25 };
Object.freeze(obj);

obj.name = 'new'; // 无效,对象被冻结
obj.newProp = 'value'; // 无效,无法添加新属性
const obj = { name: 'test', age: 25 };
Object.seal(obj);

obj.name = 'new'; // 有效,可以修改现有属性
obj.newProp = 'value'; // 无效,无法添加新属性
const obj = {};

Object.defineProperty(obj, 'name', {
  value: 'test',
  writable: true,
  enumerable: true,
  configurable: true
});

ES6+ 新特性

1
2
3
4
const person = { name: '张三', age: 25, city: '北京' };

const { name, age } = person;
const { name: userName, age: userAge } = person; // 重命名
1
2
3
4
5
const key = 'dynamicKey';
const obj = {
  [key]: 'value',
  [`${key}_suffix`]: 'another value'
};
1
2
3
4
5
6
const obj = {
  name: 'test',
  greet() { // 等价于 greet: function() {}
    return `你好,我是${this.name}`;
  }
};

对象原型和继承

function Animal(name) {
  this.name = name;
}

Animal.prototype.speak = function() {
  console.log(`${this.name} makes a noise.`);
};

function Dog(name) {
  Animal.call(this, name);
}

Dog.prototype = Object.create(Animal.prototype);
Dog.prototype.constructor = Dog;

const dog = new Dog('旺财');
dog.speak(); // '旺财 makes a noise.'
class Animal {
  constructor(name) {
    this.name = name;
  }

  speak() {
    console.log(`${this.name} makes a noise.`);
  }
}

class Dog extends Animal {
  constructor(name, breed) {
    super(name);
    this.breed = breed;
  }

  bark() {
    console.log('Woof!');
  }
}

const dog = new Dog('旺财', '金毛');
dog.speak(); // '旺财 makes a noise.'
dog.bark(); // 'Woof!'

对象深拷贝与浅拷贝

const original = { 
  name: 'test', 
  address: { city: '北京', district: '朝阳' } 
};

// 浅拷贝方法
const shallow1 = Object.assign({}, original);
const shallow2 = { ...original }; // 扩展运算符

// 浅拷贝的问题:嵌套对象仍共享引用
shallow1.address.city = '上海';
console.log(original.address.city); // '上海' - 原对象也被改变了
// 简单深拷贝(仅适用于纯数据对象)
const deepCopy = JSON.parse(JSON.stringify(original));

// 更完整的深拷贝函数
function deepClone(obj) {
  if (obj === null || typeof obj !== 'object') return obj;
  if (obj instanceof Date) return new Date(obj);
  if (obj instanceof Array) return obj.map(item => deepClone(item));
  if (typeof obj === 'object') {
    const clonedObj = {};
    for (let key in obj) {
      if (obj.hasOwnProperty(key)) {
        clonedObj[key] = deepClone(obj[key]);
      }
    }
    return clonedObj;
  }
}

实际应用场景

  1. 配置对象:存储应用程序配置
  2. 数据模型:表示业务实体
  3. 模块模式:封装相关功能
  4. 状态管理:存储应用状态
  5. API响应:处理服务端数据

JavaScript对象是语言的核心特性,理解对象的概念和操作方法对于编写高质量的JavaScript代码至关重要。