ES6 - 对象
ES6 - 对象
Section titled “ES6 - 对象”在 JavaScript 中,对象 (objects) 是基本的数据结构,用于存储键值对的集合。键通常是字符串(或 ES6+ 中的 Symbol),值可以是任何数据类型,包括其他对象或函数(方法)。ES6 引入了多项增强功能,使对象的使用更加简洁和强大。
对象字面量是创建对象的最常用方式,使用花括号 {}。
对象字面量的 ES6 增强:
Section titled “对象字面量的 ES6 增强:”- 属性简写 (Shorthand Property Names): 如果变量名与预期的属性键相同,则可以省略冒号和值。
const name = "Alice";const age = 30;
// ES5 写法// const personES5 = { name: name, age: age };
// ES6 简写const person = { name, age };console.log(person); // { name: "Alice", age: 30 }- 方法简写 (Shorthand Method Names): 您可以更简洁地定义方法。
// ES5 写法// const calculatorES5 = {// add: function(a, b) { return a + b; }// };
// ES6 简写const calculator = { add(a, b) { return a + b; }, subtract(a, b) { // 也是方法简写的一个例子 return a - b; }};console.log(calculator.add(5, 3)); // 8- 计算属性名 (Computed Property Names): 允许您在对象字面量中使用表达式作为属性键。
let propPrefix = "user";const dynamicObject = { [propPrefix + "Id"]: 123, [propPrefix + "Name"]: "Bob", [`${propPrefix}Role`]: "Admin" // 使用模板字面量};console.log(dynamicObject); // { userId: 123, userName: "Bob", userRole: "Admin" }-
- 点记法 (Dot Notation):
object.propertyName(当属性名是有效的标识符时)。
- 点记法 (Dot Notation):
-
- 方括号记法 (Bracket Notation):
object['propertyName'](当属性名是动态的、包含特殊字符的字符串或变量时)。
- 方括号记法 (Bracket Notation):
console.log(person.name); // "Alice"console.log(dynamicObject['userId']); // 123let keyToAccess = "userName";console.log(dynamicObject[keyToAccess]); // "Bob"对象构造函数
Section titled “对象构造函数”尽管对象字面量很常见,但也可以使用构造函数或 ES6 类创建对象。
1. new Object() 构造函数(不常用):
Section titled “1. new Object() 构造函数(不常用):”const car = new Object();car.make = "Ford";car.model = "Mustang";console.log(car.make); // "Ford"// 这等同于:const car = {};2. 自定义构造函数(ES6 类之前):
Section titled “2. 自定义构造函数(ES6 类之前):”function Vehicle(make, model) { this.make = make; this.model = model; this.displayInfo = function() { console.log(`Vehicle: ${this.make} ${this.model}`); };}const myVehicle = new Vehicle("Toyota", "Camry");myVehicle.displayInfo(); // "Vehicle: Toyota Camry"3. ES6 类(复杂对象的首选):
Section titled “3. ES6 类(复杂对象的首选):”// 详见“ES6 - 类”部分class Animal { constructor(name) { this.name = name; } speak() { console.log(`${this.name} makes a sound.`); }}const lion = new Animal("Leo");lion.speak(); // "Leo makes a sound."静态 Object 方法
Section titled “静态 Object 方法”Object 构造函数本身提供了几种有用的静态方法:
Object.assign(target, ...sources) (ES6)
Section titled “Object.assign(target, ...sources) (ES6)”将一个或多个源对象中所有可枚举的自身属性复制到目标对象。它返回修改后的目标对象。这是一个浅拷贝。
const target = { a: 1, b: 2 };const source1 = { b: 4, c: 5 };const source2 = { d: 6 };const merged = Object.assign(target, source1, source2);console.log(target); // { a: 1, b: 4, c: 5, d: 6 } (target 被修改)console.log(merged); // { a: 1, b: 4, c: 5, d: 6 }
// 浅克隆const original = { x: 10, y: 20 };const clone = Object.assign({}, original);console.log(clone); // { x: 10, y: 20 }clone.x = 100;console.log(original.x); // 10 (原始对象的基本类型属性不受影响)Object.create(proto, propertiesObject?)
Section titled “Object.create(proto, propertiesObject?)”创建一个新对象,其原型对象为指定的对象,并包含可选的属性。
const animalPrototype = { greet() { console.log(`Hello, I am a ${this.type}`); }};const dog = Object.create(animalPrototype);dog.type = "Dog";dog.greet(); // "Hello, I am a Dog"Object.keys(obj) (ES5)
Section titled “Object.keys(obj) (ES5)”返回给定对象自身的可枚举属性名(字符串)组成的数组。
Object.values(obj) (ES2017)
Section titled “Object.values(obj) (ES2017)”返回给定对象自身的可枚举属性值组成的数组。
Object.entries(obj) (ES2017)
Section titled “Object.entries(obj) (ES2017)”返回给定对象自身的可枚举字符串键属性 [key, value] 对组成的数组。
const user = { id: 1, username: 'testuser', email: 'test@example.com' };console.log(Object.keys(user)); // ["id", "username", "email"]console.log(Object.values(user)); // [1, "testuser", "test@example.com"]console.log(Object.entries(user)); // [["id", 1], ["username", "testuser"], ["email", "test@example.com"]]Object.getPrototypeOf(obj) 和 Object.setPrototypeOf(obj, prototype) (ES6)
Section titled “Object.getPrototypeOf(obj) 和 Object.setPrototypeOf(obj, prototype) (ES6)”获取和设置对象原型的标准方法。由于性能影响,应谨慎使用 Object.setPrototypeOf。
delete 运算符从对象中移除一个属性。
const myObj = { a: 5, b: 12 };delete myObj.a;console.log(myObj); // { b: 12 }console.log('a' in myObj); // false对象是引用类型。即使两个不同的对象具有相同的属性,它们也绝不相等(=== 或 ==),因为它们引用的是不同的内存位置。只有当两个变量指向完全相同的对象实例时,比较结果才为 true。
const obj1 = { name: "Tom" };const obj2 = { name: "Tom" };const obj3 = obj1;
console.log(obj1 === obj2); // false (内存中的不同对象)console.log(obj1 === obj3); // true (obj3 引用与 obj1 相同的对象)对象解构 (Object Destructuring) (ES6):
Section titled “对象解构 (Object Destructuring) (ES6):”一种便捷的方式,用于从对象中提取属性到不同的变量中。
const employee = { firstName: 'John', lastName: 'Doe', department: 'Engineering'};
// 基本解构const { firstName, department } = employee;console.log(firstName); // "John"console.log(department); // "Engineering"
// 使用不同变量名进行解构const { lastName: surname } = employee;console.log(surname); // "Doe"
// 使用默认值进行解构const { country = "USA" } = employee;console.log(country); // "USA"
// 在函数参数中解构function printEmployeeInfo({ firstName, department }) { console.log(`${firstName} works in ${department}.`);}printEmployeeInfo(employee); // "John works in Engineering."有关 Object 方法和特性的更多信息,请参阅 MDN:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object