AI 摘要
AI
正在生成摘要...

承接上篇基础语法革新,下篇将深入探索ES6在面向对象、异步编程和模块化领域的革命性特性

有些内容主包并没有学习过,相关代码来自于AI,主包是JAVA后端,诸如类的一些概念,JAVA中会更加深刻。除此之外重点是Promise、模块化等在Vue中使用较多。

一、类(Class):面向对象新范式

1.1 类的基本结构与继承

JAVASCRIPT
class Animal {
  // 构造函数
  constructor(name) {
    this.name = name;
    this.speed = 0;
  }
  
  // 实例方法
  run(speed) {
    this.speed = speed;
    console.log(`${this.name} runs at ${speed} km/h`);
  }
  
  // Getter
  get currentSpeed() {
    return this.speed;
  }
  
  // 静态方法
  static compare(a, b) {
    return a.speed - b.speed;
  }
}

// 继承
class Rabbit extends Animal {
  constructor(name, earLength) {
    super(name); // 必须调用super
    this.earLength = earLength;
  }
  
  // 方法重写
  run(speed) {
    super.run(speed); // 调用父类方法
    console.log(\"And jumps!\");
  }
  
  // 新方法
  hide() {
    console.log(`${this.name} hides!`);
  }
}

const rabbit = new Rabbit(\'Bunny\', 10);
rabbit.run(5); 
// Bunny runs at 5 km/h
// And jumps!

1.2 类的继承

JAVASCRIPT
// 证明类本质仍是函数
console.log(typeof Animal); // \"function\"

// 原型链验证
console.log(Rabbit.prototype.__proto__ === Animal.prototype); // true
console.log(rabbit instanceof Animal); // true

// super内部实现原理
class Parent {
  constructor() { this.id = \"parent\"; }
}

class Child extends Parent {
  constructor() {
    super(); // 等价于 Parent.call(this)
  }
}

1.3 静态属性与私有属性(ES2022补充)

JAVASCRIPT
class Database {
  // 静态属性 (ES2022)
  static version = \'1.0\';
  
  // 私有属性 (ES2022)
  #connectionString;
  
  constructor(connectionString) {
    this.#connectionString = connectionString;
  }
  
  // 私有方法
  #validateConnection() {
    return this.#connectionString.startsWith(\'http\');
  }
  
  connect() {
    if (!this.#validateConnection()) {
      throw new Error(\'Invalid connection string\');
    }
    console.log(\'Connected to database\');
  }
}

二、Promise:异步编程的革命

2.1 Promise核心概念与状态机

JAVASCRIPT
// Promise三种状态:pending, fulfilled, rejected
const fetchData = (url) => new Promise((resolve, reject) => {
  const xhr = new XMLHttpRequest();
  xhr.open(\'GET\', url);
  xhr.onload = () => resolve(xhr.responseText);
  xhr.onerror = () => reject(new Error(\'Request failed\'));
  xhr.send();
});

// 使用示例
fetchData(\'https://api.example.com/data\')
  .then(data => {
    console.log(\'Data received:\', data);
    return JSON.parse(data);
  })
  .catch(error => {
    console.error(\'Error:\', error.message);
  });

2.2 Promise链式调用与错误处理

JAVASCRIPT
const asyncOperation = () => 
  Promise.resolve(10)
    .then(value => value * 2)
    .then(value => { throw new Error(\'Something wrong\') })
    .then(() => console.log(\'This will not run\'))
    .catch(error => {
      console.error(\'Caught error:\', error.message);
      return 0; // 恢复流程
    })
    .then(value => console.log(\'Final value:\', value));

// 输出:
// Caught error: Something wrong
// Final value: 0

2.3 Promise高级组合API

JAVASCRIPT
// Promise.all: 全部成功或任意失败
Promise.all([
  fetchData(\'/api/users\'),
  fetchData(\'/api/posts\')
]).then(([users, posts]) => {
  console.log(\'All data loaded\');
});

// Promise.race: 竞速机制
Promise.race([
  fetchData(\'/api/primary\'),
  new Promise((_, reject) => 
    setTimeout(() => reject(new Error(\'Timeout\')), 5000)
  )
]).then(data => {
  console.log(\'Data received within 5 seconds\');
}).catch(error => {
  console.error(\'Request timed out\');
});

三、模块系统:import/export标准化

3.1 命名导出与导入

JAVASCRIPT
// math.js
export const PI = 3.14159;
export function square(x) { return x * x; }
export class Circle {
  constructor(r) { this.radius = r; }
  area() { return PI * this.radius ** 2; }
}

// app.js
import { PI, square, Circle } from \'./math.js\';
console.log(square(PI));

3.2 默认导出与混合导出

JAVASCRIPT
// logger.js
export default function(message) {
  console.log(`[${new Date().toISOString()}] ${message}`);
}

// 同时使用默认导出和命名导出
export const logLevels = {
  DEBUG: 0,
  INFO: 1,
  ERROR: 2
};

// app.js
import log, { logLevels } from \'./logger.js\';
log(\'System started\');
console.log(\'Current log level:\', logLevels.INFO);

3.3 动态导入与按需加载

JAVASCRIPT
// 动态加载模块
async function loadModule(moduleName) {
  try {
    const module = await import(`./modules/${moduleName}.js`);
    module.init();
  } catch (error) {
    console.error(`Failed to load module ${moduleName}:`, error);
  }
}

// 路由变化时加载对应模块
window.addEventListener(\'hashchange\', () => {
  const page = location.hash.slice(1) || \'home\';
  loadModule(page);
});

四、迭代器与生成器:可迭代协议

4.1 可迭代协议与迭代器协议

JAVASCRIPT
// 自定义可迭代对象
const range = {
  from: 1,
  to: 5,
  
  // 实现迭代器方法
  [Symbol.iterator]() {
    let current = this.from;
    let last = this.to;
    
    return {
      next() {
        if (current <= last) {
          return { value: current++, done: false };
        } else {
          return { done: true };
        }
      }
    };
  }
};

// 使用for..of遍历
for (const num of range) {
  console.log(num); // 1,2,3,4,5
}

4.2 生成器函数原理与应用

JAVASCRIPT
// 生成器函数
function* fibonacci(limit) {
  let a = 0, b = 1;
  while (a < limit) {
    yield a;
    [a, b] = [b, a + b];
  }
}

// 手动迭代
const fibGen = fibonacci(100);
console.log(fibGen.next().value); // 0
console.log(fibGen.next().value); // 1
console.log(fibGen.next().value); // 1

// 自动迭代
for (const num of fibonacci(100)) {
  console.log(num); // 0,1,1,2,3,5,8,13,21,34,55,89
}

4.3 异步生成器与迭代

JAVASCRIPT
// 异步生成器
async function* fetchPages(urls) {
  for (const url of urls) {
    const response = await fetch(url);
    yield response.json();
  }
}

// 使用for await..of
(async () => {
  const urls = [
    \'/api/page1\',
    \'/api/page2\',
    \'/api/page3\'
  ];
  
  for await (const data of fetchPages(urls)) {
    console.log(\'Page data:\', data);
  }
})();

五、Symbol:唯一标识符

5.1 Symbol基本特性

JAVASCRIPT
// 创建唯一Symbol
const id = Symbol(\'unique identifier\');
const id2 = Symbol(\'unique identifier\');

console.log(id === id2); // false

// 对象属性键
const user = {
  [id]: \'12345\', // 不会被常规方法访问
  name: \'Alice\'
};

console.log(user[id]); // \'12345\'
console.log(Object.keys(user)); // [\'name\']

5.2 内置Symbol与元编程

JAVASCRIPT
// 自定义迭代行为
const customIterable = {
  data: [10, 20, 30],
  [Symbol.iterator]() {
    let index = this.data.length;
    return {
      next: () => ({
        value: this.data[--index],
        done: index < 0
      })
    };
  }
};

// 反向迭代
for (const value of customIterable) {
  console.log(value); // 30, 20, 10
}

// Symbol.toStringTag
class CustomClass {
  get [Symbol.toStringTag]() {
    return \'MyCustomClass\';
  }
}

console.log(new CustomClass().toString()); // [object MyCustomClass]

六、其他重要特性补充

6.1 集合类型:Map与Set

JAVASCRIPT
// Map:键值对集合(键可以是任意类型)
const userMap = new Map();
userMap.set(user1, { lastLogin: \'2023-01-01\' });
userMap.set(user2, { lastLogin: \'2023-02-15\' });

console.log(userMap.get(user1));

// Set:唯一值集合
const tags = new Set();
tags.add(\'javascript\');
tags.add(\'es6\');
tags.add(\'javascript\'); // 重复值被忽略

console.log([...tags]); // [\'javascript\', \'es6\']

6.2 代理与反射:元编程利器

JAVASCRIPT
// 创建代理
const target = { message: \'hello\' };
const handler = {
  get: function(obj, prop) {
    return prop in obj ? obj[prop] : \'Not found\';
  },
  set: function(obj, prop, value) {
    if (prop === \'age\' && !Number.isInteger(value)) {
      throw new TypeError(\'Age must be an integer\');
    }
    obj[prop] = value;
    return true; // 表示设置成功
  }
};

const proxy = new Proxy(target, handler);
console.log(proxy.message); // \'hello\'
console.log(proxy.unknown); // \'Not found\'
proxy.age = 30; // 正常
proxy.age = \'thirty\'; // TypeError

6.3 二进制数据处理:ArrayBuffer与TypedArray

JAVASCRIPT
// 创建16字节缓冲区
const buffer = new ArrayBuffer(16);

// 创建32位整数视图
const int32View = new Int32Array(buffer);

// 填充数据 (每个32位整数占4字节)
for (let i = 0; i < int32View.length; i++) {
  int32View[i] = i * 2;
}

// 创建8位整数视图(共享同一缓冲区)
const int8View = new Int8Array(buffer);
console.log(int8View[4]); // 2(因为32位视图的第二个元素)

// 数据视图(处理字节序)
const dataView = new DataView(buffer);
console.log(dataView.getInt32(4)); // 读取第4字节开始的32位整数

结语:ES6的深远影响

ES6不仅是JavaScript语言的重大升级,更是现代前端开发的基石。其核心设计思想包括:

  • 标准化:统一模块化、类等社区方案
  • 现代化:引入箭头函数、解构等现代语法
  • 安全化:通过let/const、严格模式等增强可靠性
  • 异步友好:Promise奠定异步编程新范式

这些特性深刻影响了后续ECMAScript标准的演进方向,也造就了现代前端框架(React、Vue、Angular)的繁荣生态。掌握ES6是成为高级JavaScript开发者的必经之路。

评论