js 经典实现
JavaScript 的经典实现涉及多个核心概念和常用模式,涵盖基础语法、设计模式、算法优化等。以下是关键实现示例和思路:
闭包与模块化
闭包是 JavaScript 的核心特性之一,常用于封装私有变量。例如实现计数器:
function createCounter() {
let count = 0;
return {
increment: () => ++count,
getCount: () => count
};
}
const counter = createCounter();
counter.increment();
console.log(counter.getCount()); // 1
原型链继承
通过原型实现对象继承:
function Animal(name) {
this.name = name;
}
Animal.prototype.speak = function() {
console.log(`${this.name} makes a noise`);
};
function Dog(name) {
Animal.call(this, name);
}
Dog.prototype = Object.create(Animal.prototype);
Dog.prototype.constructor = Dog;
Promise 异步控制
手动实现简化版 Promise:

class MyPromise {
constructor(executor) {
this.state = 'pending';
this.value = undefined;
executor(this.resolve.bind(this), this.reject.bind(this));
}
resolve(value) {
if (this.state === 'pending') {
this.state = 'fulfilled';
this.value = value;
}
}
then(onFulfilled) {
if (this.state === 'fulfilled') {
onFulfilled(this.value);
}
return this;
}
}
函数柯里化
高阶函数应用示例:
function curry(fn) {
return function curried(...args) {
if (args.length >= fn.length) {
return fn.apply(this, args);
} else {
return (...args2) => curried.apply(this, args.concat(args2));
}
};
}
const sum = (a, b, c) => a + b + c;
const curriedSum = curry(sum);
console.log(curriedSum(1)(2)(3)); // 6
观察者模式
实现事件订阅系统:

class EventEmitter {
constructor() {
this.events = {};
}
on(event, listener) {
(this.events[event] || (this.events[event] = [])).push(listener);
}
emit(event, ...args) {
(this.events[event] || []).forEach(listener => listener(...args));
}
}
数组去重
多种实现方案对比:
// Set 方案
const uniqueArray = arr => [...new Set(arr)];
// Reduce 方案
const uniqueByReduce = arr =>
arr.reduce((acc, cur) => acc.includes(cur) ? acc : [...acc, cur], []);
深拷贝实现
递归处理对象引用:
function deepClone(obj, map = new WeakMap()) {
if (obj === null || typeof obj !== 'object') return obj;
if (map.has(obj)) return map.get(obj);
const clone = Array.isArray(obj) ? [] : {};
map.set(obj, clone);
for (let key in obj) {
if (obj.hasOwnProperty(key)) {
clone[key] = deepClone(obj[key], map);
}
}
return clone;
}
防抖与节流
性能优化常用技巧:
// 防抖
function debounce(fn, delay) {
let timer;
return function(...args) {
clearTimeout(timer);
timer = setTimeout(() => fn.apply(this, args), delay);
};
}
// 节流
function throttle(fn, interval) {
let lastTime = 0;
return function(...args) {
const now = Date.now();
if (now - lastTime >= interval) {
fn.apply(this, args);
lastTime = now;
}
};
}
这些实现涵盖了 JavaScript 的核心编程范式,理解这些经典模式有助于深入掌握语言特性。实际开发中应根据场景选择合适方案,并注意现代语法(如 ES6+)的优化写法。






