欢迎光临
我们一直在努力

ES6语法详解

1. 块级作用域(let、const)

let

let a = 10;
if (true) {
let a = 20; // 块级作用域,外面的a不受影响
console.log(a); // 20
}
console.log(a); // 10

const

不可变变量,必须初始化,不能重新赋值(对象属性可变)。

const PI = 3.14;
// PI = 3; // 报错


2. 字符串扩展

模板字符串

let name = 'Alice';
let msg = `Hello, ${name}!`;
console.log(msg); // Hello, Alice!

新增方法

  • includes()
  • startsWith()
  • endsWith()
  • repeat()

3. 解构赋值

数组解构

const [a, b, c] = [1, 2, 3];

对象解构

const {name, age} = {name: '张三', age: 18};


4. 函数扩展

默认参数

function foo(x, y=10) {
return x + y;
}

剩余参数

function sum(…args) {
return args.reduce((a,b)=>a+b, 0);
}

箭头函数

const add = (a, b) => a + b;

箭头函数不绑定自己的this和arguments。


5. 对象扩展

属性简写

let x = 1, y = 2;
let obj = {x, y}; // {x:1, y:2}

方法简写

let obj = {
foo() { return 42; }
}

对象合并

const obj1 = {a:1};
const obj2 = {…obj1, b:2};
// {a:1, b:2}


6. 新增数据结构

Set

const s = new Set([1,2,2,3]); // {1, 2, 3}

Map

const m = new Map();
m.set('x', 1);
m.set('y', 2);


7. Promise异步编程

function fetchData(){
return new Promise((resolve, reject)=>{
setTimeout(()=>resolve('数据'), 1000);
});
}
fetchData().then(data=>console.log(data));


8. 类(Class)

class Person {
constructor(name){
this.name = name;
}
sayHi(){
console.log(`Hi, ${this.name}`);
}
}


9. 模块化(import/export)

// a.js
export const foo = 1;

// b.js
import {foo} from './a.js';


10. 其他增强

  • for…of循环(可用于数组、set、map等可迭代对象)
  • Symbol类型
  • Proxy和Reflect
  • Generator函数(function*)

11. for…of 迭代循环

用于遍历可迭代对象(数组、Set、Map、字符串等)。

const arr = [10, 20, 30];
for (const item of arr) {
console.log(item);
}
// 输出 10 20 30

注意:for…of 不能直接遍历对象的属性,如果要遍历对象属性用 for…in。


12. Symbol 数据类型

Symbol 是 ES6 新增的一种原始数据类型,表示唯一值。

const s1 = Symbol('desc');
const s2 = Symbol('desc');
console.log(s1 === s2); // false

常用场景:作为对象属性名,避免属性名冲突。

const obj = {};
const sym = Symbol('id');
obj[sym] = 123;
console.log(obj); // { [Symbol(id)]: 123 }


13. Iterators 与 Generators(迭代器与生成器)

迭代器(Iterator)

让对象可以自定义遍历行为。

const arr = [100, 200];
const iter = arr[Symbol.iterator]();
console.log(iter.next()); // {value: 100, done: false}
console.log(iter.next()); // {value: 200, done: false}
console.log(iter.next()); // {value: undefined, done: true}

生成器函数(Generator)

function* 声明,配合 yield 暂停执行。

function* gen() {
yield 1;
yield 2;
return 3;
}
const g = gen();
console.log(g.next()); // {value: 1, done: false}
console.log(g.next()); // {value: 2, done: false}
console.log(g.next()); // {value: 3, done: true}

应用场景:异步流程控制、数据流处理等。


14. Proxy 和 Reflect

Proxy

用于创建对象的代理,可以拦截和自定义各种操作。

const obj = { name: 'Alice' };
const proxy = new Proxy(obj, {
get(target, prop) {
return prop in target ? target[prop] : 'Not Found';
}
});
console.log(proxy.name); // Alice
console.log(proxy.age); // Not Found

Reflect

Reflect 对象提供操作对象的静态方法,与 Proxy 拦截的方法一一对应。

const obj = {};
Reflect.set(obj, 'x', 100);
console.log(obj.x); // 100


15. 扩展参数与数组展开

剩余参数(Rest)

用于获取函数剩余参数。

function fn(x, …rest) {
console.log(x); // 1
console.log(rest); // [2, 3, 4]
}
fn(1, 2, 3, 4);

展开运算符(…)

用于数组和对象展开。

const arr1 = [1,2];
const arr2 = [3,4];
const arr = […arr1, …arr2]; // [1,2,3,4]

const o1 = {a:1};
const o2 = {b:2};
const o = {…o1, …o2}; // {a:1, b:2}


16. 模块化实战

默认导出与导入

// module.js
export default function() { console.log('default'); }
// main.js
import myFunc from './module.js';
myFunc();

命名导出与导入

// module.js
export const a = 1;
export function foo() {}
// main.js
import { a, foo } from './module.js';


17. Promise 进阶

Promise 可以链式调用和异常处理:

function delay(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}

delay(1000)
.then(() => {
console.log('1秒后输出');
return delay(500);
})
.then(() => {
console.log('再0.5秒后输出');
})
.catch(err => {
console.error('出错', err);
});


18. ES6 类和继承

class Animal {
constructor(name) {
this.name = name;
}
speak() {
console.log(this.name + ' makes a noise.');
}
}

class Dog extends Animal {
speak() {
super.speak();
console.log(this.name + ' barks.');
}
}

const d = new Dog('旺财');
d.speak();
// 旺财 makes a noise.
// 旺财 barks.


19. async/await(ES8补充,但和Promise密不可分,常和ES6结合使用)

function fetchData() {
return new Promise(resolve => setTimeout(() => resolve('数据'), 1000));
}

async function run() {
const data = await fetchData();
console.log(data); // 数据
}
run();


20. 常用 Array 方法扩展

  • find()
  • findIndex()
  • includes()
  • fill()
  • copyWithin()
  • entries(), keys(), values()

const nums = [10, 20, 30];
console.log(nums.find(n => n > 15)); // 20

21. Set 和 Map 的高级应用

Set 去重

const arr = [1, 2, 2, 3, 3];
const uniqueArr = […new Set(arr)]; // [1, 2, 3]

Map 转数组

const map = new Map([['a', 1], ['b', 2]]);
const arr = Array.from(map); // [['a', 1], ['b', 2]]

遍历 Map/Set

for (let [key, value] of map) {
console.log(key, value);
}
for (let value of new Set([1,2,3])) {
console.log(value);
}


22. Object.entries 与 Object.values

可以更方便地遍历对象的属性与值。

const obj = {x: 1, y: 2};
for (const [k, v] of Object.entries(obj)) {
console.log(k, v);
}
// x 1
// y 2

console.log(Object.values(obj)); // [1, 2]


23. 解构赋值的默认值和嵌套

默认值

const [a = 5, b = 7] = [1]; // a=1, b=7

对象嵌套解构

const obj = {foo: {bar: 123}};
const {foo: {bar}} = obj; // bar = 123

注意:解构只提取值,不改变原对象结构。


24. 浏览器与兼容性

ES6 大部分语法已被主流浏览器支持。如果要兼容旧环境(比如 IE),建议用 Babel 转译。

// Babel 示例
// src/code.js
const fn = x => x + 1;

// 转译后(兼容老浏览器的ES5)
var fn = function(x) { return x + 1; };


25. Symbol 在对象中的应用与内置Symbol

Symbol 实际用途除了属性名唯一,还可用于实现隐私数据和元编程。

内置Symbol示例

const obj = {
[Symbol.toStringTag]: 'MyObject'
};
console.log(obj.toString()); // [object MyObject]


26. Generator 与异步流程管理(进阶)

配合 co 库或自己实现简易异步同步:

function* gen() {
const res1 = yield fetch('url1');
const res2 = yield fetch('url2');
}

function run(generator) {
const g = generator();
function next(data) {
const result = g.next(data);
if (!result.done) {
result.value.then(next);
}
}
next();
}

这属于异步控制流的高级玩法,实际开发中基本都用 async/await 替代。


27. Class 进阶

静态方法与属性

class Example {
static staticMethod() {
return 'static!';
}
}
console.log(Example.staticMethod()); // static!

使用 getter/setter

class Rectangle {
constructor(width) {
this._width = width;
}
get width() {
return this._width;
}
set width(val) {
this._width = val;
}
}
const r = new Rectangle(10);
r.width = 20;
console.log(r.width); // 20

实例属性简写(ES2022+,部分环境支持)

class Point {
x = 0;
y = 0;
}


28. 对象属性的计算名与动态名

const key = 'score';
const obj = {
[key]: 99,
['hello' + 'World']: 'hello!'
};


29. ES7/ES8/ES9(附加)

  • ES7: Array.prototype.includes、指数运算符**
  • ES8: Object.values、Object.entries、字符串补全 padStart/padEnd
  • ES9: 异步迭代(for await…of)

includes 和 指数运算

const arr = [1,2,3];
console.log(arr.includes(2)); // true
console.log(2**3); // 8

padStart/padEnd

console.log('1'.padStart(3, '0')); // '001'
console.log('abc'.padEnd(5, '*')); // 'abc**'

异步迭代

async function* asyncGen() {
yield 'hello';
yield 'world';
}
(async () => {
for await (const v of asyncGen()) {
console.log(v); // hello world
}
})();


30. 最佳实践与建议

  • 优先使用 const/let,不用 var。
  • 充分运用解构和展开,提升代码可读性和效率。
  • 模块化组织代码,利于维护和复用。
  • 优先用箭头函数,注意 this 指向。
  • 用 Promise 和 async/await 处理异步,避免回调地狱。
  • 利用 Set/Map 处理大量数据结构,操作高效。

31. 箭头函数的 this、arguments 与坑点

箭头函数的特点

  • 不会绑定自己的 this,继承外层 this。
  • 没有自己的 arguments 对象。
  • 不能用作构造函数(不能 new)。
  • 没有原型(prototype)属性。

实际示例

function Timer() {
this.seconds = 0;
setInterval(() => {
this.seconds++;
console.log(this.seconds);
}, 1000);
}
new Timer(); // 能访问到 Timer 的 this

坑点:

const obj = {
fn: () => { console.log(this) }
};
obj.fn(); // this 不是 obj,而是全局(window 或 undefined)

function normal() {
console.log(this);
}
normal(); // this: window 或 undefined(严格模式)

结论:需要对象方法或事件回调用普通函数,不要用箭头函数。


32. 剩余参数和展开的结合应用

合并数组和对象

const arr1 = [1,2], arr2 = [3,4];
const arrMerged = […arr1, …arr2];

const obj1 = {a:1}, obj2 = {b:2};
const oMerged = {…obj1, …obj2}; // {a:1, b:2}

常用于 immutable 不可变数据管理,如 React 状态管理。

数组克隆与对象克隆

const arrCopy = […arr];
const objCopy = {…obj};


33. 模块化细节与实际项目组织

多种导出方式

// 导出多个
export const a = 1;
export function foo() {}

// 默认导出
export default function main() {}

模块重命名

import {foo as myFoo} from './mod.js';

整体导入

import * as api from './someApi.js';
api.method1();

动态导入(ES2020+)

import('./module.js').then(mod => {
mod.run();
});

用于路由按需加载等场景。


34. Promise 实战应用与常见坑

Promise.all / Promise.race

Promise.all([p1, p2, p3]).then(([r1, r2, r3]) => {});
Promise.race([p1, p2, p3]).then(result => {});

all 等待所有,race 谁先结束用谁。

链式捕获

Promise.resolve(1)
.then(x => x + 1)
.catch(err => console.error(err))
.finally(() => console.log('done'));

promise 嵌套运行

fetch('/api')
.then(res => res.json()) // 返回 promise
.then(data => console.log(data));

注意
  • 如果 then 或 catch 返回的是值,会继续链式下去。
  • 如果返回的是 Promise,则下一步等待 Promise resolve 后继续。
  • 不要把回调再套 promise,避免回调地狱。

35. async/await 实践与错误处理

等待多个异步结果

async function main() {
const [a, b] = await Promise.all([getA(), getB()]);
}

try/catch

async function fetchData() {
try {
const data = await fetch('api');
return data;
} catch(e) {
console.error('出错', e);
}
}

在循环内使用 await

for (let id of [1,2,3]) {
await process(id);
}

但更推荐 Promise.all 并发处理,不阻塞。


36. Class 的高级语法

私有属性(ES2022+,Node/新浏览器支持)

class Person {
#age = 0; // 私有属性,外部不可访问
setAge(age) { this.#age = age; }
getAge() { return this.#age; }
}

类静态属性和静态方法

class Counter {
static count = 0;
static inc() { Counter.count++; }
}

继承和 super

class Animal {
speak() { console.log('Animal sound'); }
}
class Dog extends Animal {
speak() {
super.speak();
console.log('Dog barks');
}
}


37. Proxy 的进阶应用:数据响应式

Proxy 常用于 Vue3 响应式原理。

function reactive(obj) {
return new Proxy(obj, {
get(target, key) {
console.log('get', key);
return target[key];
},
set(target, key, value) {
console.log('set', key, value);
target[key] = value;
return true;
}
});
}

const r = reactive({a:1});
r.a = 2; // set a 2
console.log(r.a); // get a


38. Symbol 原理与扩展应用

枚举唯一常量

const STATUS = {
READY: Symbol('ready'),
WAIT: Symbol('wait'),
DONE: Symbol('done')
};
function doSomething(status) {
if (status === STATUS.READY) { … }
}


39. Generator、异步迭代与 for await…of

配合处理大批量、流式数据等场景。

async function* getData() {
yield await fetch('/api/1');
yield await fetch('/api/2');
}
for await (const res of getData()) {
console.log(await res.json());
}


40. 常用小技巧

  • 数组去重:[…new Set(arr)]
  • 对象合并:{…obj1, …obj2}
  • 默认参数优化:函数内用 参数 = 参数 || 默认值
  • 快速定义数组或对象的新属性:arr.push(…array2) 或 Object.assign(obj, {key: value})

41. 常见问题与最佳实践

  • 避免 var,始终用 let/const
  • 优先用箭头函数简化回调,但注意 this 指向场景
  • 模块作用域隔离,代码更安全
  • 多用解构,简化代码
  • 异步流程用 async/await 控制,异常捕获用 try/catch
  • 数据变更用展开实现不可变数据流,为 React/Vue 推荐写法
赞(0)
未经允许不得转载:171主机测评 » ES6语法详解
分享到: 更多 (0)

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址