跳到主要内容

ES6 主要新特性

先总结

  1. 块级作用域 let 和 const
  2. symbol 符号
  3. 解构赋值

1. 块级作用域,新增了 let 和 const

  • 块级作用域是指由一对花括号 {} 包裹的代码块中定义的变量,这些变量在代码块外部是不可见的。
  • 这是一个在 ES6 中引入的概念,旨在提供比传统的函数作用域更细粒度的变量控制方式。
  • 在块级作用域中,可以使用 letconst 关键字声明变量,这些变量的作用域被限制在声明它们的块中。
块级作用域示例
function testFun(x) {
var a = 0;
let b = 0;
{
var c = 1; // 未使用let或const,c没有块级作用域,属于 testFun 的函数作用域
let d = 1; // d具有块级作用域,只能在当前代码块中访问
}
// 在这里,变量c是可访问的,但变量d不是
}

在上述代码中,变量c使用var声明,因此它没有块级作用域,而是属于函数testFun的作用域。相反,变量d使用let声明,因此它具有块级作用域,只能在它被声明的那个块内访问。

循环中的块级作用域

for (let i = 0; i < 5; i++) {
// 在这里,i具有块级作用域
}
// 在这里,i不再可访问

在这个例子中,每次循环迭代时,变量 i 都是在一个新的块级作用域中声明的,因此在循环外部它是不可访问的。

块级作用域与闭包

  • 块级作用域对于理解闭包也非常重要。闭包允许函数访问并操作函数外部的变量。
  • 在块级作用域中声明的变量,如果被一个内部函数引用,那么这个内部函数就形成了一个闭包。
function outer() {
let outerVar = "我在外面";
{
let innerVar = "我在里面";
function innerFunc() {
console.log(outerVar); // 访问外部变量,形成闭包
console.log(innerVar); // 访问内部变量
}
innerFunc();
}
// 在这里,innerVar 不可访问,但 outerVar 仍然可访问
}

在这个例子中,innerFunc 函数形成了一个闭包,因为它访问了外部函数 outer 中的变量 outerVar,以及它自己块级作用域中的变量 innerVar

  • 块级作用域是一个强大的特性,它提供了更细粒度的控制变量可见性的能力。
  • 通过使用 letconst ,开发者可以确保变量只在需要的地方可见,从而减少错误和提高代码的可维护性。
  • ES6 及以后的版本中,块级作用域已成为 JavaScript 中管理变量的首选方式。

2. symbol 符号语义,用于创建唯一标识符

  • Symbol 是 ES6 中引入的一种新的基本数据类型,用于表示一个独一无二的值,不能与其他数据类型进行运算。
  • 它是 JavaScript 中的第七种数据类型,与 undefined、null、Number(数值)、String(字符串)、Boolean(布尔值)、Object(对象)并列。

3. 解构赋值

  • 解构赋值(Destructuring Assignment)
const person = { name: "Alice", age: 25 };
const { name, age } = person;
console.log(name, age); // 输出: Alice 25

const numbers = [1, 2, 3, 4];
const [first, second, ...rest] = numbers;
console.log(first, second, rest); // 输出: 1 2 [3, 4]

4. 字符串方面

4.1 模板字面量 我的名字 ${myname}

  • 模板字面量(Template Literals)
const name = "Alice";
const greeting = `Hello, ${name}!`;
console.log(greeting); // 输出: Hello, Alice!

4.1 字符串添加了一些新方法

const str = "Hello, World!";

console.log(str.startsWith("Hello")); // 输出: true
console.log(str.endsWith("World!")); // 输出: true
console.log(str.includes("lo")); // 输出: true

console.log(str.repeat(3)); // 输出: Hello, World!Hello, World!Hello, World!
console.log(str.padStart(20, "X")); // 输出: XXXXHello, World!
console.log(str.padEnd(20, "Y")); // 输出: Hello, World!YYYY

5. 对象方法

5.1 Set 和 Map 数据结构

  • Set 和 Map 数据结构
// Set 示例
const set = new Set([1, 2, 3, 4, 5]);
set.add(6);
console.log(set.has(3)); // 输出: true
console.log(set.size); // 输出: 6
set.delete(4);
console.log(set.size); // 输出: 5

// Map 示例
const map = new Map();
map.set("name", "Alice");
map.set("age", 25);
console.log(map.get("name")); // 输出: Alice
console.log(map.size); // 输出: 2
map.delete("age");
console.log(map.size); // 输出: 1

5.3 函数方面 添加了一些新方法

  • Array.from()方法
  • includes()方法
  • map()、filter() 方法
  • forEach()方法
  • find()方法
  • some()、every() 方法

5.3 箭头函数 ()=>

  • 箭头函数(Arrow Functions)
const add = (a, b) => a + b;
console.log(add(2, 3)); // 输出: 5

const numbers = [1, 2, 3, 4];
const squaredNumbers = numbers.map((num) => num * num);
console.log(squaredNumbers); // 输出: [1, 4, 9, 16]

5.4 默认参数

  • 默认参数(Default Parameters)
function greet(name = "Guest") {
console.log(`Hello, ${name}!`);
}

greet(); // 输出: Hello, Guest!
greet("Alice"); // 输出: Hello, Alice!

6. 扩展运算符 [...arr1]

  • 扩展运算符 Spread Operator
const arr1 = [1, 2, 3];
const arr2 = [...arr1, 4, 5];
console.log(arr2); // 输出: [1, 2, 3, 4, 5]

const obj1 = { name: "Alice", age: 25 };
const obj2 = { ...obj1, profession: "Engineer" };
console.log(obj2); // 输出: { name: 'Alice', age: 25, profession: 'Engineer' }

8. 迭代器和生成器

  • 迭代器和生成器(Iterators and Generators)
// 迭代器示例
function* fibonacci() {
let a = 0;
let b = 1;

while (true) {
yield a;
[a, b] = [b, a + b];
}
}

const generator = fibonacci();
console.log(generator.next().value); // 输出: 0
console.log(generator.next().value); // 输出: 1
console.log(generator.next().value); // 输出: 1

// 生成器示例
function* generateSequence() {
yield 1;
yield 2;
yield 3;
}

const sequence = Array.from(generateSequence());
console.log(sequence); // 输出: [1, 2, 3]

9. 模块化

  • 模块化(Modules)
export function add(a, b) {
return a + b;
}

export function multiply(a, b) {
return a * b;
}

// main.js
import { add, multiply } from "./math.js";

console.log(add(2, 3)); // 输出: 5
console.log(multiply(2, 3)); // 输出: 6

10. 类 class

  • 类(Class)
class Person {
constructor(name) {
this.name = name;
}

sayHello() {
console.log(`Hello, my name is ${this.name}.`);
}
}

const person = new Person("Alice");
person.sayHello(); // 输出: Hello, my name is Alice.

11. 管道操作符

  • 管道操作符(Pipeline Operator)
const add = (x, y) => x + y;
const double = (x) => x * 2;
const square = (x) => x * x;
const result = 5 |> add(3) |> double |> square;
console.log(result); // 输出: 64

12. 异步函数

  • 异步函数(Async Functions)
function delay(t) {
return new Promise((resolve) => setTimeout(resolve, t));
}

async function process() {
console.log("Start");
await delay(2000);
console.log("End");
}

process();
// 输出:
// Start
// (等待2秒)
// End

15. Promise

function fetchUserData() {
return new Promise((resolve, reject) => {
// 模拟异步请求
setTimeout(() => {
const user = {
name: "Alice",
age: 25,
};
resolve(user);
}, 2000);
});
}

fetchUserData()
.then((user) => {
console.log(
`Hello, my name is ${user.name} and I'm ${user.age} years old.`
);
})
.catch((error) => {
console.log("Error:", error);
});

16. Reflect

Reflect 是一个内置的对象,它提供拦截 JavaScript 操作的方法。

  • Reflect 不是一个函数对象,因此它是不可构造的。

静态方法

  1. Reflect.get(target, propertyKey[, receiver])

  2. Reflect.set(target, propertyKey, value[, receiver])

  3. Reflect.has(target, propertyKey)

  4. Reflect.deleteProperty(target, propertyKey)

  5. Reflect.construct(target, argumentsList[, newTarget])

  6. Reflect.apply(target, thisArgument, argumentsList)

  7. Reflect.defineProperty(target, propertyKey, attributes)

  8. Reflect.getOwnPropertyDescriptor(target, propertyKey)

  9. Reflect.isExtensible(target)

  10. Reflect.preventExtensions(target)

  11. Reflect.ownKeys(target)

  12. Reflect.setPrototypeOf(target, prototype)

  13. Reflect.getPrototypeOf(target)

const target = {
name: "Alice",
};
const handler = {
get(target, property) {
return property in target ? target[property] : "Not found";
},
};
const proxy = new Proxy(target, handler);

17. Proxy