112 Enhanced Object Literals(ES6 增强对象字面量)笔记

一、核心概念引入

  • 对象字面量定义:通过{}语法直接在代码中编写的对象,例如const restaurant = { name: 'ABC', address: 'XX街' },是 JavaScript 中创建对象的常用方式。
  • ES6 增强目的:简化对象字面量的编写语法,提升代码简洁性和可读性,主要包含 3 种增强方式。

二、增强方式 1:简化属性赋值(属性名与变量名一致时)

2.1 语法对比

时期 语法示例 核心差异
ES6 之前 需重复写属性名和变量名:const openingHours = { mon: '9:00-21:00', tue: '9:00-21:00' };``const restaurant = { openingHours: openingHours // 重复书写openingHours``}; 属性名与变量名一致时,需手动重复赋值,代码冗余
ES6 之后 直接写变量名,自动映射为属性:const openingHours = { mon: '9:00-21:00', tue: '9:00-21:00' };``const restaurant = { openingHours // 仅写变量名,自动生成同名属性``}; 省略重复的属性名,语法更简洁,逻辑更清晰

2.2 例题实践

题目:定义变量menu(存储餐厅菜单)和rating(存储餐厅评分),使用 ES6 增强语法将其加入restaurant对象,并打印对象查看结果。

解答

javascript

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
// 1. 定义外部变量
const menu = {
breakfast: ["egg", "milk", "bread"],
lunch: ["steak", "salad", "soup"],
dinner: ["fish", "pasta", "dessert"],
};
const rating = 4.8;

// 2. 使用ES6增强语法创建对象
const restaurant = {
name: "Green Leaf",
address: "123 Main Street",
menu, // 自动映射为menu: menu
rating, // 自动映射为rating: rating
};

// 3. 打印结果
console.log(restaurant);
/* 输出:
{
name: 'Green Leaf',
address: '123 Main Street',
menu: { breakfast: [...], lunch: [...], dinner: [...] },
rating: 4.8
}
*/

2.3 注意事项

  • 若后续修改外部变量名,对象内的属性名也需同步修改,否则 JavaScript 无法识别变量(例如将openingHours改为hours,对象内也需写hours,而非保留openingHours)。

三、增强方式 2:简化方法编写(省略function关键字)

3.1 语法对比

时期 语法示例 核心差异
ES6 之前 需显式写function关键字和分号:const restaurant = { order: function(food1, food2) { return [food1, food2]; }, // 需写function和分号 getRating: function() { return this.rating; }``}; 定义对象方法时,需手动写function关键字,语法繁琐
ES6 之后 直接写 “方法名 () {}”,省略function和分号:const restaurant = { rating: 4.8, order(food1, food2) { // 省略function return [food1, food2]; }, getRating() { // 省略function return this.rating; }``}; 省略function关键字,语法更简洁,与其他编程语言(如 Java)的方法定义更接近

3.2 例题实践

题目:为restaurant对象添加orderDinner方法(接收 2 个参数,返回晚餐菜品组合)和getMenuType方法(接收 “早餐 / 午餐 / 晚餐” 参数,返回对应菜单),使用 ES6 简化语法编写,并调用方法验证结果。

解答

javascript

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
const restaurant = {
menu: {
breakfast: ["egg", "milk", "bread"],
lunch: ["steak", "salad", "soup"],
dinner: ["fish", "pasta", "dessert"],
},
// ES6简化方法:orderDinner
orderDinner(dish1, dish2) {
return `Your dinner: ${dish1} + ${dish2}`;
},
// ES6简化方法:getMenuType
getMenuType(type) {
// 统一将输入转为小写,避免大小写问题
const lowerType = type.toLowerCase();
return this.menu[lowerType] || `Sorry, no ${type} menu`;
},
};

// 调用方法
console.log(restaurant.orderDinner("fish", "dessert"));
// 输出:Your dinner: fish + dessert

console.log(restaurant.getMenuType("LUNCH"));
// 输出:['steak', 'salad', 'soup']

console.log(restaurant.getMenuType("snack"));
// 输出:Sorry, no snack menu

3.3 注意事项

  • 语法选择:若偏好明确看到function关键字(认为更直观),可保留旧语法;若追求简洁,推荐使用 ES6 新语法(VS Code 等编辑器会将方法名标为绿色,便于区分)。
  • this指向不变:新语法定义的方法,this指向仍与旧语法一致(指向调用方法的对象,如restaurant.getRating()this指向restaurant)。

四、增强方式 3:支持计算属性名(动态生成属性名)

4.1 语法对比

时期 语法示例 核心差异
ES6 之前 仅能计算属性值,无法计算属性名:const restaurant = { // 只能计算值(如12+12=24),属性名需手动写死 'openHour-mon': 12 + 12, // 属性名固定为'openHour-mon' 'openHour-tue': 12 + 12``}; 属性名必须手动书写,无法通过表达式动态生成
ES6 之后 使用[]包裹表达式,动态计算属性名:const weekdays = ['mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun']; const restaurant = { // 计算属性名:weekdays[0] = 'mon',生成属性名'openHour-mon' [openHour-{weekdays[0]}]: '9:00-21:00',  // 计算属性名:weekdays[1] = 'tue',生成属性名'openHour-tue'
  [openHour-{weekdays[1]}]: '9:00-21:00'};
支持通过表达式(数组索引、字符串拼接、算术运算等)动态生成属性名,灵活性更高

4.2 例题实践

题目:定义数组seasons(存储四季:[‘spring’, ‘summer’, ‘autumn’, ‘winter’]),为restaurant对象动态生成 “季节特色菜品” 属性(如special-spring),每个属性值为对应季节的特色菜数组,最后打印对象查看结果。

解答

javascript

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
const seasons = ["spring", "summer", "autumn", "winter"];

// 动态生成季节特色菜品属性
const restaurant = {
name: "Green Leaf",
// 计算属性名:`special-${seasons[0]}` → 'special-spring'
[`special-${seasons[0]}`]: ["asparagus", "pea soup", "strawberry cake"],
// 计算属性名:`special-${seasons[1]}` → 'special-summer'
[`special-${seasons[1]}`]: [
"watermelon salad",
"grilled shrimp",
"lemon sorbet",
],
// 计算属性名:`special-${seasons[2]}` → 'special-autumn'
[`special-${seasons[2]}`]: ["pumpkin soup", "roast turkey", "apple pie"],
// 计算属性名:`special-${seasons[3]}` → 'special-winter'
[`special-${seasons[3]}`]: ["hot pot", "beef stew", "chocolate fondue"],
};

// 打印结果
console.log(restaurant);
/* 输出:
{
name: 'Green Leaf',
'special-spring': ['asparagus', 'pea soup', 'strawberry cake'],
'special-summer': ['watermelon salad', 'grilled shrimp', 'lemon sorbet'],
'special-autumn': ['pumpkin soup', 'roast turkey', 'apple pie'],
'special-winter': ['hot pot', 'beef stew', 'chocolate fondue']
}
*/

// 访问动态生成的属性(需用[]语法,不能用.语法)
console.log(restaurant["special-autumn"]);
// 输出:['pumpkin soup', 'roast turkey', 'apple pie']

4.3 注意事项

  • 计算属性名的表达式需用[]包裹,且支持任意合法表达式(如算术运算[2+2]→属性名4,但无实际意义,仅作演示)。
  • 访问动态生成的属性时,若属性名含特殊字符(如-),需用对象[属性名字符串]语法(如restaurant['special-spring']),不能用对象.属性名语法(restaurant.special-spring会报错)。