| name | JavaScript ES6+特性 |
| description | 当使用现代JavaScript时,分析ES6+特性,优化代码结构,解决兼容性问题。验证语法应用,设计模块化架构,和最佳实践。 |
| license | MIT |
JavaScript ES6+特性技能
概述
ES6+(ECMAScript 2015及后续版本)为JavaScript带来了大量现代化特性,显著提升了语言的表达能力和开发效率。不当的特性使用会导致兼容性问题、性能下降、代码可读性差。
核心原则: 好的ES6+代码应该简洁明了、性能优良、兼容性好、易于维护。坏的ES6+代码会过度复杂、性能损耗、兼容性差。
何时使用
始终:
- 开发现代Web应用时
- 构建前端框架时
- 处理异步编程时
- 优化代码结构时
- 提升开发效率时
- 团队协作开发时
触发短语:
- "如何使用箭头函数?"
- "ES6+最佳实践"
- "Promise和async/await区别"
- "解构赋值怎么用?"
- "模块化编程方案"
- "ES6+性能优化"
JavaScript ES6+技能功能
变量与作用域
- let和const关键字
- 块级作用域
- 暂时性死区
- 变量提升差异
函数特性
对象与数组
- 对象字面量增强
- 数组方法扩展
- 解构赋值
- 扩展运算符
异步编程
- Promise对象
- async/await语法
- Generator函数
- 迭代器和可迭代对象
模块系统
- ES6模块语法
- 动态导入
- 命名导出和默认导出
- 循环依赖处理
常见问题
兼容性问题
性能问题
-
问题: 过度使用解构赋值
-
原因: 频繁的对象创建和销毁
-
解决: 合理使用解构,避免性能热点
-
问题: 箭头函数滥用
-
原因: 不理解this绑定差异
-
解决: 根据场景选择合适的函数类型
代码质量问题
- 问题: 模块导入混乱
- 原因: 缺乏统一的模块组织策略
- 解决: 建立清晰的模块导入规范
代码示例
变量声明与作用域
function variableDeclarations() {
console.log(varVar);
var varVar = 'var变量';
let letVar = 'let变量';
const constVar = 'const变量';
if (true) {
var blockVar = '块内var变量';
let blockLet = '块内let变量';
const blockConst = '块内const变量';
}
console.log(blockVar);
return { varVar, letVar, constVar };
}
function constantsExample() {
const person = {
name: '张三',
age: 30
};
person.age = 31;
person.city = '北京';
numbers = [, , ];
numbers.();
{ person, numbers };
}
箭头函数与普通函数对比
const arrowFunctions = {
basic: () => 'Hello World',
withParams: (name, age) => `${name}今年${age}岁`,
withDefaults: (name = '匿名', age = 0) => `${name}今年${age}岁`,
multiLine: (x, y) => {
const sum = x + y;
const product = x * y;
return { sum, product };
},
objectReturn: (name, age) => ({ name, age })
};
function thisBindingExample() {
const person = {
name: '张三',
age: 30,
sayNameNormal: function() {
console.log(this.name);
setTimeout(() {
.(.);
}, );
},
: () {
.(.);
( {
.(.);
}, );
},
: {
.(.);
}
};
person;
}
() {
.(arrowFunctions.());
.(arrowFunctions.(, ));
.(arrowFunctions.());
.(arrowFunctions.(, ));
.(arrowFunctions.(, ));
person = ();
person.();
person.();
person.();
}
解构赋值应用
function objectDestructuring() {
const user = {
id: 1,
name: '张三',
email: 'zhangsan@example.com',
profile: {
age: 30,
city: '北京',
hobbies: ['编程', '阅读', '旅游']
}
};
const { name, email } = user;
console.log(name, email);
const { name: userName, email: userEmail } = user;
console.log(userName, userEmail);
const { name: n = '匿名', phone = '未设置' } = user;
console.log(n, phone);
const { profile: { age, city } } = user;
console.log(age, city);
const {
profile: {
: userAge,
: [firstHobby]
}
} = user;
.(userAge, firstHobby);
() {
;
}
(user);
}
() {
colors = [, , , ];
[first, second, third] = colors;
.(first, second, third);
[, , thirdColor] = colors;
.(thirdColor);
[primary, ...others] = colors;
.(primary, others);
[a, b, c, d = ] = colors;
.(d);
x = , y = ;
[x, y] = [y, x];
.(x, y);
() {
[, , ];
}
[xCoord, yCoord, zCoord] = ();
.(xCoord, yCoord, zCoord);
{ first, second, third, primary, others };
}
模板字符串应用
function templateStrings() {
const name = '张三';
const age = 30;
const city = '北京';
const message = `你好,我是${name},今年${age}岁,来自${city}。`;
console.log(message);
const html = `
<div class="user-card">
<h2>${name}</h2>
<p>年龄: ${age}</p>
<p>城市: ${city}</p>
</div>
`;
console.log(html);
const price = 100;
const tax = 0.08;
const total = `总价: $${price} (含税: $${(price * tax).toFixed(2)})`;
console.log(total);
const formatName = (name) => name.toUpperCase();
const greeting = `你好,${formatName(name)}!`;
console.log(greeting);
const status = age >= ? : ;
description = ;
.(description);
{ message, html, total, greeting, description };
}
() {
() {
strings.( {
value = values[i] ? : ;
result + string + value;
}, );
}
name = ;
age = ;
highlighted = highlight;
.(highlighted);
() {
strings.( {
value = values[i] !== ? : ;
result + string + value;
}, );
}
tableName = ;
userId = ;
query = sql;
.(query);
{ highlighted, query };
}
Promise与async/await
function promiseBasics() {
const fetchUser = (userId) => {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (userId > 0) {
resolve({
id: userId,
name: `用户${userId}`,
email: `user${userId}@example.com`
});
} else {
reject(new Error('用户ID必须大于0'));
}
}, 1000);
});
};
fetchUser(1)
.then(user => {
console.log('获取用户成功:', user);
return user.name;
})
.then(name => {
console.log('用户名:', name);
})
.catch( {
.(, error);
})
.( {
.();
});
= () => {
{
user = (userId);
formattedUser = (user);
savedUser = (formattedUser);
savedUser;
} (error) {
.(, error);
error;
}
};
= () => {
{
users = .(
userIds.( (id))
);
users;
} (error) {
.(, error);
[];
}
};
= () => {
.([
(userId),
(
( ( ()), timeout)
)
]);
};
{ fetchUser, processUser, fetchMultipleUsers, fetchWithTimeout };
}
() {
= () => {
{
response = ();
user = response.();
processedUser = {
...user,
: ,
: user. ===
};
processedUser;
} (error) {
.(, error);
error;
}
};
= () => {
{
[user, posts] = .([
(userId),
(userId)
]);
{
user,
posts,
: posts.
};
} (error) {
.(, error);
error;
}
};
= () => {
{
user = (userData);
profile = (user., {
: userData.,
: userData.
});
(user.);
{ user, profile };
} (error) {
.(, error);
error;
}
};
= () => {
( i = ; i < maxRetries; i++) {
{
response = (url);
(response.) {
response.();
}
();
} (error) {
(i === maxRetries - ) {
error;
}
.(, error.);
( (resolve, * (i + )));
}
}
};
{ getUserInfo, getUserWithPosts, createUserWithProfile, fetchWithRetry };
}
类与继承
class Person {
#id;
#secret;
constructor(name, age, id) {
this.name = name;
this.age = age;
this.#id = id;
this.#secret = 'private data';
}
getInfo() {
return {
name: this.name,
age: this.age,
id: this.#id
};
}
get displayName() {
return `${this.name} (${this.age}岁)`;
}
set age(newAge) {
if (newAge >= 0 && newAge <= 150) {
this.age = newAge;
} else {
throw new Error('年龄必须在0-150之间');
}
}
static () {
(name, , id);
}
#() {
age >= && age <= ;
}
() {
(.#(newAge)) {
. = newAge;
;
}
;
}
}
{
#salary;
#department;
() {
(name, age, id);
.#salary = salary;
.#department = department;
}
() {
baseInfo = .();
{
...baseInfo,
: .#salary,
: .#department
};
}
() {
.#salary * ;
}
() {
.#salary;
}
() {
(newSalary >= ) {
.#salary = newSalary;
} {
();
}
}
() {
(name, , id, , );
}
}
() {
person = (, , );
.(person.());
.(person.);
adult = .(, );
.(adult.());
employee = (, , , , );
.(employee.());
.(employee.());
manager = .(, );
.(manager.());
{ person, adult, employee, manager };
}
模块系统
export const PI = 3.14159;
export function add(a, b) {
return a + b;
}
export function multiply(a, b) {
return a * b;
}
export class Calculator {
constructor() {
this.result = 0;
}
add(value) {
this.result += value;
return this;
}
multiply(value) {
this.result *= value;
return this;
}
getResult() {
return this.result;
}
}
export default class AdvancedCalculator extends Calculator {
power(exponent) {
this.result = .(., exponent);
;
}
() {
. = .(.);
;
}
}
, { , add, multiply, } ;
* ;
() {
calc = ();
result = calc.().().().().();
.(, result);
.(, );
.(, (, ));
.(, (, ));
simpleCalc = .();
simpleCalc.().();
.(, simpleCalc.());
() {
{
mathModule = ();
.(, mathModule.);
= mathModule.;
dynamicCalc = ();
dynamicCalc.().();
.(, dynamicCalc.());
} (error) {
.(, error);
}
}
();
{ calc, result, simpleCalc };
}
迭代器和生成器
class NumberRange {
constructor(start, end, step = 1) {
this.start = start;
this.end = end;
this.step = step;
}
[Symbol.iterator]() {
let current = this.start;
return {
next: () => {
if (current <= this.end) {
const value = current;
current += this.step;
return { value, done: false };
} else {
return { value: undefined, done: true };
}
}
};
}
}
function* fibonacciGenerator() {
let a = 0, b = 1;
while (true) {
yield a;
[a, b] = [b, a + b];
}
}
function* idGenerator(start = 1) {
id = start;
() {
id++;
}
}
() {
range = (, );
.([...range]);
( num range) {
.(num);
}
fib = ();
.(fib.().);
.(fib.().);
.(fib.().);
.(fib.().);
first10Fib = [];
fibGen = ();
( i = ; i < ; i++) {
first10Fib.(fibGen.().);
}
.(, first10Fib);
idGen = ();
.(, idGen.().);
.(, idGen.().);
* () {
();
();
();
}
= () => {
asyncGen = ();
( response asyncGen) {
data = response.();
.(, data);
}
};
{ range, first10Fib, idGen };
}
最佳实践
代码风格
- 优先使用const: 只在需要重新赋值时使用let
- 箭头函数: 适合回调函数,避免在方法中使用
- 模板字符串: 优先使用模板字符串替代字符串拼接
- 解构赋值: 提高代码可读性,避免重复访问
性能优化
- 避免过度解构: 在性能敏感代码中谨慎使用解构
- 合理使用Promise: 避免不必要的Promise包装
- 模块懒加载: 使用动态导入减少初始加载时间
- 内存管理: 及时清理事件监听器和定时器
兼容性处理
- Babel转译: 确保代码在目标环境中运行
- Polyfill: 为缺失的特性提供兼容实现
- 特性检测: 使用特性检测而非浏览器检测
- 渐进增强: 在支持的环境中使用新特性
相关技能
- react-components - React组件开发
- state-management - 状态管理
- frontend - 前端开发
- testing-frontend - 前端测试
- performance-optimization - 性能优化