JavaScript
约 4333 字大约 14 分钟
JavaScript
数据类型 🟢
1. 基本数据类型
- Number
- String
- Boolean
- Undefined
- Null
- Symbol (ES6)
- BigInt (ES2020)
2. 引用数据类型
- Object
- Array
- Function
- Date
- RegExp
- Map/Set
3. 类型判断
// typeof 操作符
typeof 42; // "number"
typeof "abc"; // "string"
typeof true; // "boolean"
typeof undefined; // "undefined"
typeof null; // "object" (这是一个历史遗留bug)
typeof Symbol(); // "symbol"
typeof 42n; // "bigint"
// instanceof 操作符
[] instanceof Array; // true
new Date() instanceof Date; // true
// Object.prototype.toString.call()
Object.prototype.toString.call([]); // "[object Array]"
Object.prototype.toString.call(new Date()); // "[object Date]"
// Array.isArray()
Array.isArray([]); // true
Array.isArray({}); // false
4. 类型转换
// 显式转换
Number('123'); // 123
String(123); // "123"
Boolean(123); // true
// 隐式转换
'123' - 0; // 123
123 + ''; // "123"
!!123; // true
// 常见坑点
[] + []; // ""
[] + {}; // "[object Object]"
{} + []; // 0
true + true; // 2
'5' + 3; // "53"
'5' - 3; // 2
作用域和闭包 🟡
1. 作用域类型
- 全局作用域
- 函数作用域
- 块级作用域(ES6)
// 全局作用域
var globalVar = 'global';
// 函数作用域
function foo() {
var functionVar = 'function';
console.log(globalVar); // 可访问
console.log(functionVar); // 可访问
}
// 块级作用域
{
let blockVar = 'block';
const constVar = 'const';
}
// console.log(blockVar); // ReferenceError
2. 闭包详解
// 基本闭包
function createCounter() {
let count = 0;
return {
increment() {
count++;
return count;
},
decrement() {
count--;
return count;
},
getCount() {
return count;
}
};
}
const counter = createCounter();
counter.increment(); // 1
counter.increment(); // 2
counter.decrement(); // 1
// 闭包实现私有变量
function createPerson(name) {
let _age = 0; // 私有变量
return {
getName() {
return name;
},
setAge(age) {
if (age >= 0 && age <= 120) {
_age = age;
}
},
getAge() {
return _age;
}
};
}
3. this绑定
// 默认绑定
function foo() {
console.log(this); // window or global
}
// 隐式绑定
const obj = {
name: 'obj',
foo() {
console.log(this.name);
}
};
// 显式绑定
function bar() {
console.log(this.name);
}
bar.call(obj); // "obj"
bar.apply(obj); // "obj"
const boundBar = bar.bind(obj);
// new绑定
function Person(name) {
this.name = name;
}
const person = new Person('John');
// 箭头函数
const arrowFn = () => {
console.log(this); // 继承外层作用域的this
};
原型链和继承 🟡
1. 原型链基础
// 构造函数
function Animal(name) {
this.name = name;
}
// 原型方法
Animal.prototype.sayName = function() {
console.log(this.name);
};
// 实例
const cat = new Animal('Cat');
cat.sayName(); // "Cat"
// 原型链查找
cat.toString(); // 从Object.prototype继承而来
2. 继承方式
// 1. 原型链继承
function Dog(name) {
this.name = name;
}
Dog.prototype = new Animal();
Dog.prototype.constructor = Dog;
// 2. 构造函数继承
function Bird(name) {
Animal.call(this, name);
}
// 3. 组合继承
function Fish(name) {
Animal.call(this, name);
}
Fish.prototype = new Animal();
Fish.prototype.constructor = Fish;
// 4. 寄生组合继承
function inherit(Child, Parent) {
const prototype = Object.create(Parent.prototype);
prototype.constructor = Child;
Child.prototype = prototype;
}
// 5. ES6 class继承
class Mammal extends Animal {
constructor(name) {
super(name);
}
}
Event Loop 🟡
1. 事件循环机制
console.log('1'); // 同步任务
setTimeout(() => {
console.log('2'); // 宏任务
}, 0);
Promise.resolve()
.then(() => {
console.log('3'); // 微任务
});
console.log('4'); // 同步任务
// 输出顺序:1, 4, 3, 2
2. 宏任务和微任务
// 宏任务
setTimeout(() => {}, 0);
setInterval(() => {}, 0);
setImmediate(() => {}); // Node.js
requestAnimationFrame(() => {}); // 浏览器
// 微任务
Promise.resolve().then(() => {});
process.nextTick(() => {}); // Node.js
MutationObserver // 浏览器
Promise和异步编程 🟡
1. Promise基础
// 创建Promise
const promise = new Promise((resolve, reject) => {
// 异步操作
if (/* 成功 */) {
resolve(value);
} else {
reject(error);
}
});
// 使用Promise
promise
.then(value => {
// 处理成功
})
.catch(error => {
// 处理错误
})
.finally(() => {
// 总是执行
});
// Promise方法
Promise.all([promise1, promise2])
.then(values => {
// 所有promise都完成
});
Promise.race([promise1, promise2])
.then(value => {
// 第一个完成的promise
});
Promise.allSettled([promise1, promise2])
.then(results => {
// 所有promise都已settled
});
2. Async/Await
async function fetchData() {
try {
const response = await fetch('api/data');
const data = await response.json();
return data;
} catch (error) {
console.error('Error:', error);
throw error;
}
}
// 并行执行
async function fetchMultiple() {
const [data1, data2] = await Promise.all([
fetchData('api/1'),
fetchData('api/2')
]);
return { data1, data2 };
}
ES6+新特性 🟢
1. 变量声明
// let和const
let x = 1;
const y = 2;
// 暂时性死区
console.log(z); // ReferenceError
let z = 3;
2. 解构赋值
// 数组解构
const [a, b, ...rest] = [1, 2, 3, 4];
// 对象解构
const { name, age, ...others } = person;
// 默认值
const { title = 'Untitled' } = post;
3. 模板字符串
const name = 'World';
const greeting = `Hello ${name}!`;
// 标签模板
function tag(strings, ...values) {
return strings.reduce((result, str, i) =>
`${result}${str}${values[i] || ''}`
, '');
}
4. 箭头函数
// 基本语法
const add = (a, b) => a + b;
// 返回对象
const getUser = () => ({
name: 'John',
age: 30
});
// 箭头函数与this
class Counter {
constructor() {
this.count = 0;
// 箭头函数绑定this
this.increment = () => {
this.count++;
};
}
}
// 不适用箭头函数的场景
const obj = {
value: 0,
// 方法定义不使用箭头函数
increment() {
this.value++;
}
};
5. Class类
// 基本类定义
class Person {
// 私有属性
#privateField;
// 静态属性
static species = 'human';
constructor(name) {
this.name = name;
this.#privateField = 'private';
}
// 实例方法
sayHello() {
console.log(`Hello, ${this.name}`);
}
// getter/setter
get upperName() {
return this.name.toUpperCase();
}
set upperName(value) {
this.name = value.toLowerCase();
}
// 静态方法
static create(name) {
return new Person(name);
}
}
// 继承
class Employee extends Person {
constructor(name, role) {
super(name);
this.role = role;
}
}
6. 模块化
// 导出
export const name = 'Module';
export function hello() {}
export default class MyClass {}
// 导入
import MyClass, { name, hello } from './module';
import * as module from './module';
// 动态导入
const myModule = await import('./module');
函数式编程 🟡
1. 纯函数
// 纯函数示例
const add = (a, b) => a + b;
// 非纯函数示例
let count = 0;
const increment = () => ++count;
// 纯函数实践
const updateArray = (arr, index, value) => [
...arr.slice(0, index),
value,
...arr.slice(index + 1)
];
2. 高阶函数
// 函数作为参数
const map = (arr, fn) => arr.map(fn);
// 函数作为返回值
const multiply = (x) => (y) => x * y;
// 实际应用
const compose = (...fns) =>
fns.reduce((f, g) => (...args) => f(g(...args)));
const pipe = (...fns) =>
fns.reduce((f, g) => (...args) => g(f(...args)));
3. 柯里化
// 基础柯里化
const curry = (fn) => {
const arity = fn.length;
return function curried(...args) {
if (args.length >= arity) {
return fn(...args);
}
return (...moreArgs) => curried(...args, ...moreArgs);
};
};
// 实际应用
const add = (x, y, z) => x + y + z;
const curriedAdd = curry(add);
curriedAdd(1)(2)(3); // 6
curriedAdd(1, 2)(3); // 6
异步编程进阶 🔴
1. Promise进阶
// Promise.all 变体
const promiseAllSettled = (promises) => {
return Promise.all(
promises.map(p =>
Promise.resolve(p)
.then(value => ({
status: 'fulfilled',
value
}))
.catch(reason => ({
status: 'rejected',
reason
}))
)
);
};
// Promise队列
const promiseQueue = (tasks, concurrency = 1) => {
let running = 0;
let taskIndex = 0;
const results = [];
return new Promise((resolve) => {
function runTask() {
if (taskIndex === tasks.length && running === 0) {
resolve(results);
return;
}
while (running < concurrency && taskIndex < tasks.length) {
const index = taskIndex++;
running++;
Promise.resolve(tasks[index]())
.then(result => {
results[index] = result;
running--;
runTask();
})
.catch(error => {
results[index] = error;
running--;
runTask();
});
}
}
runTask();
});
};
2. Generator函数
// 基本用法
function* numberGenerator() {
yield 1;
yield 2;
return 3;
}
// 异步Generator
async function* asyncGenerator() {
const response = await fetch('api/data');
yield await response.json();
}
// 实现Iterator
class Collection {
constructor(items) {
this.items = items;
}
*[Symbol.iterator]() {
for (let item of this.items) {
yield item;
}
}
}
3. 异步迭代器
// 异步迭代器实现
class AsyncQueue {
constructor() {
this.queue = [];
this.pendingPromise = null;
}
enqueue(value) {
this.queue.push(value);
this.notifyPending();
}
notifyPending() {
if (this.pendingPromise && this.queue.length > 0) {
const { resolve } = this.pendingPromise;
const value = this.queue.shift();
resolve({ value, done: false });
this.pendingPromise = null;
}
}
async *[Symbol.asyncIterator]() {
while (true) {
if (this.queue.length > 0) {
yield this.queue.shift();
} else {
await new Promise(resolve => {
this.pendingPromise = { resolve };
});
}
}
}
}
设计模式 🔴
1. 单例模式
class Singleton {
static instance = null;
constructor() {
if (Singleton.instance) {
return Singleton.instance;
}
Singleton.instance = this;
}
static getInstance() {
if (!Singleton.instance) {
Singleton.instance = new Singleton();
}
return Singleton.instance;
}
}
2. 观察者模式
class EventEmitter {
constructor() {
this.events = {};
}
on(event, callback) {
if (!this.events[event]) {
this.events[event] = [];
}
this.events[event].push(callback);
return () => this.off(event, callback);
}
off(event, callback) {
if (!this.events[event]) return;
this.events[event] = this.events[event]
.filter(cb => cb !== callback);
}
emit(event, data) {
if (!this.events[event]) return;
this.events[event].forEach(callback => {
callback(data);
});
}
once(event, callback) {
const wrapper = (...args) => {
callback(...args);
this.off(event, wrapper);
};
this.on(event, wrapper);
}
}
3. 工厂模式
// 简单工厂
class UserFactory {
static createUser(type) {
switch (type) {
case 'admin':
return new AdminUser();
case 'regular':
return new RegularUser();
default:
throw new Error('Invalid user type');
}
}
}
// 抽象工厂
class AbstractFactory {
createButton() {
throw new Error('Abstract method');
}
createInput() {
throw new Error('Abstract method');
}
}
class MaterialUIFactory extends AbstractFactory {
createButton() {
return new MaterialButton();
}
createInput() {
return new MaterialInput();
}
}
JavaScript性能优化 🔴
1. 内存优化
// 内存泄漏示例及解决方案
class Component {
constructor() {
this.handleClick = this.handleClick.bind(this);
document.addEventListener('click', this.handleClick);
}
destroy() {
// 清理事件监听
document.removeEventListener('click', this.handleClick);
}
// WeakMap/WeakSet使用
static cache = new WeakMap();
static getData(obj) {
if (!Component.cache.has(obj)) {
const data = expensiveOperation(obj);
Component.cache.set(obj, data);
}
return Component.cache.get(obj);
}
}
2. 代码优化
// 避免重复计算
const memoize = (fn) => {
const cache = new Map();
return (...args) => {
const key = JSON.stringify(args);
if (!cache.has(key)) {
cache.set(key, fn(...args));
}
return cache.get(key);
};
};
// 使用Web Workers处理密集计算
const worker = new Worker('worker.js');
worker.postMessage({ data: complexData });
worker.onmessage = (e) => {
console.log('计算结果:', e.data);
};
3. 渲染优化
// 虚拟列表实现
class VirtualList {
constructor(container, items, itemHeight) {
this.container = container;
this.items = items;
this.itemHeight = itemHeight;
this.visibleItems = Math.ceil(container.clientHeight / itemHeight);
this.scrollHandler = this.onScroll.bind(this);
this.container.addEventListener('scroll', this.scrollHandler);
this.render();
}
onScroll() {
requestAnimationFrame(() => this.render());
}
render() {
const scrollTop = this.container.scrollTop;
const startIndex = Math.floor(scrollTop / this.itemHeight);
const endIndex = startIndex + this.visibleItems;
// 渲染可见区域的项目
const visibleContent = this.items
.slice(startIndex, endIndex)
.map(item => `<div style="height: ${this.itemHeight}px">${item}</div>`)
.join('');
this.container.innerHTML = visibleContent;
}
}
高级面试题 🔴
1. 原型链相关
Q1: 实现继承的多种方式及其优缺点? A1:
// 1. 原型链继承
function Parent() {}
function Child() {}
Child.prototype = new Parent();
// 优点:简单
// 缺点:所有实例共享属性,无法传参
// 2. 构造函数继承
function Child() {
Parent.call(this);
}
// 优点:可以传参
// 缺点:无法继承原型方法
// 3. 组合继承
function Child() {
Parent.call(this);
}
Child.prototype = new Parent();
// 优点:结合了前两种方式的优点
// 缺点:调用了两次父构造函数
// 4. 寄生组合继承
function Child() {
Parent.call(this);
}
Child.prototype = Object.create(Parent.prototype);
Child.prototype.constructor = Child;
// 优点:最优解决方案
// 缺点:实现较复杂
2. 闭包相关
Q1: 闭包的实际应用场景有哪些? A1:
// 1. 数据私有化
function createCounter() {
let count = 0;
return {
increment() { return ++count; },
decrement() { return --count; }
};
}
// 2. 函数工厂
function multiply(x) {
return function(y) {
return x * y;
};
}
// 3. 模块化
const module = (function() {
let private = 0;
return {
increment() { private++; },
getCount() { return private; }
};
})();
3. 异步编程相关
Q1: 实现一个带并发限制的异步任务调度器 A1:
class Scheduler {
constructor(limit) {
this.limit = limit;
this.running = 0;
this.queue = [];
}
async add(promiseCreator) {
if (this.running >= this.limit) {
await new Promise(resolve => {
this.queue.push(resolve);
});
}
this.running++;
try {
const result = await promiseCreator();
return result;
} finally {
this.running--;
if (this.queue.length > 0) {
const next = this.queue.shift();
next();
}
}
}
}
// 使用示例
const scheduler = new Scheduler(2);
const timeout = (time) => new Promise(r => setTimeout(r, time));
scheduler.add(() => timeout(1000).then(() => console.log(1)));
scheduler.add(() => timeout(500).then(() => console.log(2)));
scheduler.add(() => timeout(300).then(() => console.log(3)));
scheduler.add(() => timeout(400).then(() => console.log(4)));
深入JavaScript运行机制 🔴
1. JavaScript引擎工作原理
// V8引擎执行过程
// 1. 源码 -> AST
// 2. AST -> 字节码
// 3. 字节码 -> 机器码
// 示例:简单的AST结构
const ast = {
type: "Program",
body: [{
type: "VariableDeclaration",
declarations: [{
type: "VariableDeclarator",
id: {
type: "Identifier",
name: "x"
},
init: {
type: "Literal",
value: 42
}
}]
}]
};
2. 垃圾回收机制
// 标记清除算法示例
function example() {
let obj1 = { a: 1 }; // 创建对象
let obj2 = { b: 2 }; // 创建对象
obj1.ref = obj2; // 创建引用
obj2.ref = obj1; // 创建循环引用
obj1 = null; // 解除引用
obj2 = null; // 解除引用
// 此时两个对象都将被回收
}
// WeakMap/WeakSet使用示例
const cache = new WeakMap();
function memorize(fn) {
return function(obj) {
if (!cache.has(obj)) {
cache.set(obj, fn(obj));
}
return cache.get(obj);
};
}
3. 内存泄漏
// 1. 闭包导致的内存泄漏
function leakExample() {
const largeData = new Array(1000000);
return function() {
console.log(largeData[0]);
};
}
// 2. 事件监听器未移除
class Component {
constructor() {
this.handleClick = this.handleClick.bind(this);
document.addEventListener('click', this.handleClick);
}
destroy() {
// 必须移除事件监听
document.removeEventListener('click', this.handleClick);
}
}
// 3. 定时器未清除
class Timer {
start() {
this.timer = setInterval(() => {
console.log('tick');
}, 1000);
}
stop() {
clearInterval(this.timer);
}
}
JavaScript高级特性 🔴
1. Proxy和Reflect
// Proxy基本使用
const handler = {
get(target, property) {
console.log(`访问属性:${property}`);
return Reflect.get(target, property);
},
set(target, property, value) {
console.log(`设置属性:${property} = ${value}`);
return Reflect.set(target, property, value);
}
};
const proxy = new Proxy({}, handler);
// 实现只读对象
function readonly(target) {
return new Proxy(target, {
set() {
throw new Error('只读对象不可修改');
},
deleteProperty() {
throw new Error('只读对象不可删除属性');
}
});
}
// 实现验证
function validate(target, validator) {
return new Proxy(target, {
set(target, property, value) {
if (validator(property, value)) {
return Reflect.set(target, property, value);
}
throw new Error('验证失败');
}
});
}
2. 装饰器
// 类装饰器
function logged(constructor) {
return class extends constructor {
constructor(...args) {
super(...args);
console.log(`创建实例:${constructor.name}`);
}
};
}
// 方法装饰器
function measure(target, name, descriptor) {
const original = descriptor.value;
descriptor.value = async function(...args) {
const start = performance.now();
const result = await original.apply(this, args);
const end = performance.now();
console.log(`${name} 执行时间:${end - start}ms`);
return result;
};
return descriptor;
}
// 属性装饰器
function nonenumerable(target, name) {
Object.defineProperty(target, name, {
enumerable: false,
writable: true
});
}
@logged
class Example {
@nonenumerable
name = 'example';
@measure
async heavyOperation() {
// 耗时操作
}
}
3. Generator高级应用
// 实现迭代器
function* range(start, end) {
for (let i = start; i <= end; i++) {
yield i;
}
}
// 异步迭代器
async function* asyncRange(start, end) {
for (let i = start; i <= end; i++) {
await new Promise(resolve => setTimeout(resolve, 1000));
yield i;
}
}
// 协程实现
function* coroutine() {
const result1 = yield task1();
const result2 = yield task2(result1);
return result2;
}
// Generator自动执行器
function run(generator) {
const iterator = generator();
function handle(result) {
if (result.done) return Promise.resolve(result.value);
return Promise.resolve(result.value)
.then(res => handle(iterator.next(res)))
.catch(err => handle(iterator.throw(err)));
}
return handle(iterator.next());
}
4. WebAssembly集成
// 加载WebAssembly模块
async function loadWasm() {
const response = await fetch('module.wasm');
const buffer = await response.arrayBuffer();
const module = await WebAssembly.compile(buffer);
const instance = await WebAssembly.instantiate(module);
return instance.exports;
}
// 使用WebAssembly函数
async function example() {
const wasm = await loadWasm();
const result = wasm.fibonacci(10);
console.log(result);
}
// 共享内存
const memory = new WebAssembly.Memory({ initial: 10, maximum: 100 });
const array = new Int32Array(memory.buffer);
高级算法实现 🔴
1. 防抖和节流
// 防抖
function debounce(fn, delay) {
let timer = null;
return function(...args) {
clearTimeout(timer);
timer = setTimeout(() => {
fn.apply(this, args);
}, delay);
};
}
// 节流
function throttle(fn, delay) {
let last = 0;
return function(...args) {
const now = Date.now();
if (now - last >= delay) {
fn.apply(this, args);
last = now;
}
};
}
// 带取消功能的防抖
function debounceWithCancel(fn, delay) {
let timer = null;
function debounced(...args) {
clearTimeout(timer);
timer = setTimeout(() => {
fn.apply(this, args);
}, delay);
}
debounced.cancel = function() {
clearTimeout(timer);
timer = null;
};
return debounced;
}
2. 深拷贝
function deepClone(obj, hash = new WeakMap()) {
if (obj === null || typeof obj !== 'object') {
return obj;
}
// 处理循环引用
if (hash.has(obj)) {
return hash.get(obj);
}
// 处理日期
if (obj instanceof Date) {
return new Date(obj);
}
// 处理正则
if (obj instanceof RegExp) {
return new RegExp(obj);
}
// 处理数组和对象
const clone = Array.isArray(obj) ? [] : {};
hash.set(obj, clone);
Reflect.ownKeys(obj).forEach(key => {
clone[key] = deepClone(obj[key], hash);
});
return clone;
}
3. 实现Promise
class MyPromise {
constructor(executor) {
this.state = 'pending';
this.value = undefined;
this.reason = undefined;
this.onFulfilledCallbacks = [];
this.onRejectedCallbacks = [];
const resolve = value => {
if (this.state === 'pending') {
this.state = 'fulfilled';
this.value = value;
this.onFulfilledCallbacks.forEach(fn => fn());
}
};
const reject = reason => {
if (this.state === 'pending') {
this.state = 'rejected';
this.reason = reason;
this.onRejectedCallbacks.forEach(fn => fn());
}
};
try {
executor(resolve, reject);
} catch (e) {
reject(e);
}
}
then(onFulfilled, onRejected) {
onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : value => value;
onRejected = typeof onRejected === 'function' ? onRejected : reason => { throw reason };
const promise2 = new MyPromise((resolve, reject) => {
if (this.state === 'fulfilled') {
setTimeout(() => {
try {
const x = onFulfilled(this.value);
resolvePromise(promise2, x, resolve, reject);
} catch (e) {
reject(e);
}
});
}
if (this.state === 'rejected') {
setTimeout(() => {
try {
const x = onRejected(this.reason);
resolvePromise(promise2, x, resolve, reject);
} catch (e) {
reject(e);
}
});
}
if (this.state === 'pending') {
this.onFulfilledCallbacks.push(() => {
setTimeout(() => {
try {
const x = onFulfilled(this.value);
resolvePromise(promise2, x, resolve, reject);
} catch (e) {
reject(e);
}
});
});
this.onRejectedCallbacks.push(() => {
setTimeout(() => {
try {
const x = onRejected(this.reason);
resolvePromise(promise2, x, resolve, reject);
} catch (e) {
reject(e);
}
});
});
}
});
return promise2;
}
catch(onRejected) {
return this.then(null, onRejected);
}
finally(callback) {
return this.then(
value => MyPromise.resolve(callback()).then(() => value),
reason => MyPromise.resolve(callback()).then(() => { throw reason })
);
}
static resolve(value) {
return new MyPromise(resolve => resolve(value));
}
static reject(reason) {
return new MyPromise((resolve, reject) => reject(reason));
}
static all(promises) {
return new MyPromise((resolve, reject) => {
const results = [];
let count = 0;
promises.forEach((promise, index) => {
MyPromise.resolve(promise).then(
value => {
results[index] = value;
count++;
if (count === promises.length) {
resolve(results);
}
},
reject
);
});
});
}
static race(promises) {
return new MyPromise((resolve, reject) => {
promises.forEach(promise => {
MyPromise.resolve(promise).then(resolve, reject);
});
});
}
}
function resolvePromise(promise2, x, resolve, reject) {
if (promise2 === x) {
reject(new TypeError('Chaining cycle'));
}
if (x && (typeof x === 'object' || typeof x === 'function')) {
let used = false;
try {
const then = x.then;
if (typeof then === 'function') {
then.call(
x,
y => {
if (used) return;
used = true;
resolvePromise(promise2, y, resolve, reject);
},
r => {
if (used) return;
used = true;
reject(r);
}
);
} else {
resolve(x);
}
} catch (e) {
if (used) return;
used = true;
reject(e);
}
} else {
resolve(x);
}
}
JavaScript高级特性补充 🔴
1. ES6+新特性深入
1.1 Symbol深入理解
// Symbol的基本使用
const symbol1 = Symbol('description');
const symbol2 = Symbol('description');
console.log(symbol1 === symbol2); // false
// Symbol.for和Symbol.keyFor
const globalSymbol = Symbol.for('global');
console.log(Symbol.keyFor(globalSymbol)); // 'global'
// 内置Symbol值
const obj = {
[Symbol.iterator]: function* () {
yield 1;
yield 2;
},
[Symbol.toPrimitive](hint) {
switch (hint) {
case 'number':
return 123;
case 'string':
return 'str';
default:
return 'default';
}
}
};
1.2 Proxy高级应用
// 实现观察者模式
function observe(obj, callback) {
return new Proxy(obj, {
set(target, property, value) {
const oldValue = target[property];
const result = Reflect.set(target, property, value);
if (oldValue !== value) {
callback(property, value, oldValue);
}
return result;
},
deleteProperty(target, property) {
const oldValue = target[property];
const result = Reflect.deleteProperty(target, property);
if (result) {
callback(property, undefined, oldValue);
}
return result;
}
});
}
// 实现私有属性
function createPrivateObject() {
const privateData = new WeakMap();
return new Proxy({}, {
get(target, property) {
return privateData.get(target)[property];
},
set(target, property, value) {
let data = privateData.get(target);
if (!data) {
data = {};
privateData.set(target, data);
}
data[property] = value;
return true;
}
});
}
1.3 Reflect API详解
// Reflect基本用法
const obj = {};
Reflect.defineProperty(obj, 'name', {
value: 'John',
writable: false
});
// 函数调用
const fn = function(a, b) { return a + b; };
const result = Reflect.apply(fn, null, [1, 2]);
// 构造函数调用
class Person {
constructor(name) {
this.name = name;
}
}
const instance = Reflect.construct(Person, ['John']);
// 属性描述符操作
const desc = Reflect.getOwnPropertyDescriptor(obj, 'name');
2. 异步编程高级模式
2.1 异步迭代器实现
class AsyncIterator {
constructor(array) {
this.array = array;
this.index = 0;
}
async next() {
if (this.index < this.array.length) {
// 模拟异步操作
await new Promise(resolve => setTimeout(resolve, 1000));
return {
value: this.array[this.index++],
done: false
};
}
return { done: true };
}
[Symbol.asyncIterator]() {
return this;
}
}
// 使用示例
async function example() {
const iterator = new AsyncIterator([1, 2, 3]);
for await (const value of iterator) {
console.log(value);
}
}
2.2 异步生成器高级用法
async function* asyncGenerator() {
let id = 1;
while (true) {
const response = await fetch(`https://api.example.com/data/${id}`);
if (!response.ok) break;
yield await response.json();
id++;
}
}
// 分页加载示例
async function loadPages() {
const generator = asyncGenerator();
const pages = [];
try {
for await (const page of generator) {
pages.push(page);
if (pages.length >= 10) break;
}
} catch (error) {
console.error('加载失败:', error);
}
return pages;
}
3. 函数式编程进阶
3.1 函数组合
// 函数组合实现
const compose = (...fns) => x => fns.reduceRight((v, f) => f(v), x);
const pipe = (...fns) => x => fns.reduce((v, f) => f(v), x);
// 带错误处理的函数组合
const composeWithError = (...fns) => async x => {
try {
return await fns.reduceRight(async (v, f) => f(await v), x);
} catch (error) {
console.error('Composition error:', error);
throw error;
}
};
// 示例用法
const addOne = x => x + 1;
const double = x => x * 2;
const toString = x => x.toString();
const composed = compose(toString, double, addOne);
console.log(composed(5)); // "12"
3.2 函数记忆化高级实现
function memoize(fn, options = {}) {
const {
maxSize = 1000,
keyGenerator = (...args) => JSON.stringify(args),
ttl = Infinity
} = options;
const cache = new Map();
const timestamps = new Map();
return function(...args) {
const key = keyGenerator(...args);
const now = Date.now();
// 检查缓存是否过期
if (timestamps.has(key)) {
const timestamp = timestamps.get(key);
if (now - timestamp > ttl) {
cache.delete(key);
timestamps.delete(key);
}
}
if (cache.has(key)) {
return cache.get(key);
}
// 限制缓存大小
if (cache.size >= maxSize) {
const oldestKey = timestamps.keys().next().value;
cache.delete(oldestKey);
timestamps.delete(oldestKey);
}
const result = fn.apply(this, args);
cache.set(key, result);
timestamps.set(key, now);
return result;
};
}
// 使用示例
const expensiveFunction = memoize(
(n) => {
console.log('计算中...');
return n * 2;
},
{
maxSize: 100,
ttl: 5000, // 5秒缓存
keyGenerator: (n) => n.toString()
}
);
4. 元编程技术
4.1 装饰器模式进阶
// 方法装饰器
function log(target, name, descriptor) {
const original = descriptor.value;
descriptor.value = async function(...args) {
console.log(`Calling ${name} with args:`, args);
try {
const result = await original.apply(this, args);
console.log(`Result from ${name}:`, result);
return result;
} catch (error) {
console.error(`Error in ${name}:`, error);
throw error;
}
};
return descriptor;
}
// 类装饰器
function singleton(constructor) {
let instance;
return new Proxy(constructor, {
construct(target, args) {
if (!instance) {
instance = Reflect.construct(target, args);
}
return instance;
}
});
}
// 属性装饰器
function validate(validator) {
return function(target, key) {
let value = target[key];
Object.defineProperty(target, key, {
get() {
return value;
},
set(newValue) {
if (!validator(newValue)) {
throw new Error('验证失败');
}
value = newValue;
}
});
};
}
// 使用示例
@singleton
class Database {
@validate(value => typeof value === 'string')
connectionString;
@log
async query(sql) {
// 数据库查询
}
}
4.2 Symbol高级应用
// 自定义迭代器
class Range {
constructor(start, end) {
this[Symbol.iterator] = function* () {
for (let i = start; i <= end; i++) {
yield i;
}
};
}
[Symbol.toPrimitive](hint) {
switch (hint) {
case 'number':
return this.end - this.start + 1;
case 'string':
return `${this.start}..${this.end}`;
default:
return this.toString();
}
}
[Symbol.search](string) {
// 自定义搜索行为
}
[Symbol.replace](string, replacement) {
// 自定义替换行为
}
}
5. 高级设计模式
5.1 发布订阅模式
class EventEmitter {
constructor() {
this.events = new Map();
}
on(event, callback, options = {}) {
const { once = false, priority = 0 } = options;
if (!this.events.has(event)) {
this.events.set(event, []);
}
const listeners = this.events.get(event);
const listener = {
callback,
once,
priority
};
listeners.push(listener);
listeners.sort((a, b) => b.priority - a.priority);
}
off(event, callback) {
if (!this.events.has(event)) return;
const listeners = this.events.get(event);
const index = listeners.findIndex(l => l.callback === callback);
if (index !== -1) {
listeners.splice(index, 1);
}
}
emit(event, ...args) {
if (!this.events.has(event)) return;
const listeners = this.events.get(event);
const removeIndexes = [];
listeners.forEach((listener, index) => {
listener.callback.apply(this, args);
if (listener.once) {
removeIndexes.unshift(index);
}
});
removeIndexes.forEach(index => {
listeners.splice(index, 1);
});
}
once(event, callback, priority = 0) {
this.on(event, callback, { once: true, priority });
}
}
[未完待续...]