// ES5的var问题演示functionvarProblem(){console.log(i);// 输出undefined,变量提升但未赋值for(var i =0; i <3; i++){setTimeout(function(){console.log(i);// 全部输出3,共享同一个i},100);}}// ES6的解决方案functionletSolution(){// console.log(j); // 报错,暂时性死区for(let j =0; j <3; j++){setTimeout(function(){console.log(j);// 输出0,1,2,每个j独立},100);}constPI=3.1415;// PI = 3; // 报错,常量不可重新赋值const user ={name:'Alice'};user.name ='Bob';// 允许,const只限制绑定不可变}
二、箭头函数:=>的魅力
与传统函数对比
特性
传统函数
箭头函数
this指向
调用时决定
定义时决定(词法作用域)
arguments
有
无
构造函数
可以
不可以
简洁性
一般
更简洁
代码示例
// ES5函数varadd=function(a, b){return a + b;};// ES6箭头函数基础constadd=(a, b)=> a + b;// 上下文保持的典型场景const team ={members:['Alice','Bob'],teamName:'Super Squad',// ES5需要额外保存thises5Method:function(){var self =this;returnthis.members.map(function(member){return member +' is in '+ self.teamName;});},// ES6直接使用箭头函数es6Method:function(){returnthis.members.map(member=>`${member} is in ${this.teamName}`);}};// 注意事项constbadConstruct=()=>({});// new badConstruct(); // 报错,箭头函数不能作为构造函数
三、解构赋值:数据拆箱艺术
解构类型表
解构类型
示例
用途
数组解构
const [a, b] = [1, 2]
提取数组值
对象解构
const {name, age} = user
提取对象属性
嵌套解构
const {a: {b}} = obj
提取嵌套属性
默认值
const {name='Anon'} = obj
防止undefined
参数解构
function f({name}) {...}
提取函数参数
代码示例
// 1. 数组解构const rgb =[255,128,64];const[red, green, blue]= rgb;
console.log(red);// 255// 跳过某些元素const[first,, third]=['a','b','c'];// 剩余运算符const[head,...tail]=[1,2,3,4];
console.log(tail);// [2, 3, 4]// 2. 对象解构const user ={name:'Alice',age:25,address:{city:'Beijing'}};const{ name, age }= user;const{address:{ city }}= user;// 重命名 + 默认值const{name: userName, gender ='unknown'}= user;// 3. 函数参数解构functiongreet({ name, age }){console.log(`Hello ${name}, you are ${age}`);}greet(user);// 4. 交换变量值let a =1, b =2;[a, b]=[b, a];// 交换a和b
// 1. 基本用法const name ='Alice';const age =25;// ES5var str1 ='Hello '+ name +', you are '+ age +' years old';// ES6const str2 =`Hello ${name}, you are ${age} years old`;// 2. 多行字符串const poem =`Roses are red,Violets are blue,Sugar is sweet,And so are you.
`;// 3. 表达式计算const a =10, b =20;
console.log(`The sum is ${a + b}`);// The sum is 30// 4. 标签模板(高级用法)functionhighlight(strings,...values){let result ='';strings.forEach((str, i)=>{result += str;if(values[i]){result +=`<span class="highlight">${values[i]}</span>`;}});return result;}const output = highlight`Hello ${name}, you are ${age} years old`;// 输出带高亮标签的HTML字符串
六、模块系统:代码组织革命
import/export 类型
类型
语法
用途
命名导出
export const name
导出多个值
默认导出
export default func
模块主要导出
命名导入
import { name }
导入特定值
默认导入
import module
导入默认导出
全部导入
import * as module
导入整个模块
代码示例
// math.js - 导出模块exportconstPI=3.14159;exportfunctionsum(a, b){return a + b;}exportdefaultfunctionmultiply(a, b){return a * b;}// app.js - 导入模块import mult,{PI, sum }from'./math.js';// mult是默认导入,PI和sum是命名导入console.log(PI);// 3.14159
console.log(sum(2,3));// 5
console.log(mult(2,3));// 6// 重命名导入import{PIas piValue }from'./math.js';// 整体导入import*as math from'./math.js';
console.log(math.PI);
七、Class语法:面向对象升级
对比ES5原型 vs ES6 Class
特性
ES5原型
ES6 Class
语法
函数+原型
class关键字
继承
原型链
extends
构造函数
普通函数
constructor
静态方法
直接赋值
static关键字
私有字段
无
ES2022的#
代码示例
// ES5写法functionAnimalES5(name){this.name = name;}AnimalES5.prototype.speak=function(){console.log(this.name +' makes a noise.');};// ES6写法classAnimal{constructor(name){this.name = name;}speak(){console.log(`${this.name} makes a noise.`);}// 静态方法staticinfo(){console.log('This is an Animal class');}}// 继承classDogextendsAnimal{constructor(name, breed){super(name);// 调用父类构造函数this.breed = breed;}speak(){super.speak();// 调用父类方法console.log(`${this.name} barks.`);}}const d =newDog('Rex','Labrador');
d.speak();// Rex makes a noise.// Rex barks.// 静态方法调用
Animal.info();// 私有字段(ES2022)classPerson{#age;// 私有字段constructor(name, age){this.name = name;this.#age = age;}getAge(){returnthis.#age;}}const p =newPerson('Alice',25);
console.log(p.name);// Alice// console.log(p.#age); // 报错
console.log(p.getAge());// 25