JavaScript常見函數類型和用途實現場景分析
在 JavaScript 中,除了惰性函數和防抖函數外,還有許多其他有用的函數模式和功能函數。以下是一些常見的函數類型和用途:
1. 節(jié)流函數 (Throttle)
作用: 控制函數執(zhí)行的頻率,在一定時間間隔內只執(zhí)行一次,即使事件被頻繁觸發(fā)。
實現:
function throttle(func, delay) {
let lastTime = 0;
return function (...args) {
const now = Date.now();
if (now - lastTime >= delay) {
lastTime = now;
func.apply(this, args);
}
};
}應用場景:
- 滾動事件監(jiān)聽 (
scroll) - 瀏覽器窗口大小調整 (
resize)
2. 柯里化函數 (Currying)
作用: 將一個接受多個參數的函數轉換為一系列只接受一個參數的函數。
實現:
function curry(func) {
return function curried(...args) {
if (args.length >= func.length) {
return func.apply(this, args);
} else {
return function (...nextArgs) {
return curried.apply(this, args.concat(nextArgs));
};
}
};
}
// 示例
function add(a, b, c) {
return a + b + c;
}
const curriedAdd = curry(add);
console.log(curriedAdd(1)(2)(3)); // 6應用場景:
- 參數復用
- 提高代碼可讀性
3. 記憶化函數 (Memoization)
作用: 緩存函數的計算結果,避免重復計算,提高性能。
實現:
function memoize(func) {
const cache = new Map();
return function (...args) {
const key = JSON.stringify(args);
if (cache.has(key)) {
return cache.get(key);
}
const result = func.apply(this, args);
cache.set(key, result);
return result;
};
}
// 示例
function slowFunction(num) {
console.log("Calculating...");
return num * 2;
}
const memoizedFunction = memoize(slowFunction);
console.log(memoizedFunction(5)); // Calculating... 10
console.log(memoizedFunction(5)); // 10 (從緩存中獲取)應用場景:
- 動態(tài)規(guī)劃
- 遞歸計算(如斐波那契數列)
4. 高階函數 (Higher-Order Functions)
作用: 接受函數作為參數,或返回另一個函數。
示例:
function higherOrderFunction(callback) {
return function (...args) {
console.log("Before callback");
const result = callback(...args);
console.log("After callback");
return result;
};
}
// 示例
const wrappedFunction = higherOrderFunction((x, y) => x + y);
console.log(wrappedFunction(3, 4));應用場景:
- 函數式編程
- 中間件設計
5. 單例模式函數 (Singleton)
作用: 確保一個類或函數只實例化一次。
實現:
function Singleton() {
let instance;
return function () {
if (!instance) {
instance = { name: "Singleton Instance" };
}
return instance;
};
}
const getInstance = Singleton();
console.log(getInstance() === getInstance()); // true應用場景:
- 全局狀態(tài)管理
- 配置管理
6. 偏函數 (Partial Function)
作用: 固定函數的一部分參數,返回一個新的函數。
實現:
function partial(func, ...fixedArgs) {
return function (...remainingArgs) {
return func.apply(this, [...fixedArgs, ...remainingArgs]);
};
}
// 示例
function multiply(a, b, c) {
return a * b * c;
}
const partialMultiply = partial(multiply, 2);
console.log(partialMultiply(3, 4)); // 24應用場景:
- 參數預設
- 簡化函數調用
7. 自執(zhí)行函數 (IIFE)
作用: 定義后立即執(zhí)行,避免變量污染。
示例:
(function () {
const a = 10;
console.log("IIFE executed:", a);
})();應用場景:
- 模塊化開發(fā)
- 立即初始化代碼
8. 工廠函數 (Factory Function)
作用: 動態(tài)創(chuàng)建對象或函數實例。
示例:
function createPerson(name, age) {
return {
name,
age,
greet() {
console.log(`Hi, my name is ${name}`);
}
};
}
const person = createPerson("Alice", 25);
person.greet();應用場景:
- 動態(tài)對象創(chuàng)建
- 替代類構造函數
9. 遞歸函數
作用: 函數調用自身,用于解決分治問題或重復性任務。
示例:
function factorial(n) {
if (n === 1) return 1;
return n * factorial(n - 1);
}
console.log(factorial(5)); // 120應用場景:
樹結構遍歷遞歸算法(如歸并排序)
10. 管道函數 (Pipeline Function)
作用: 將函數按順序組合執(zhí)行,類似于管道。
實現:
function pipe(...funcs) {
return function (value) {
return funcs.reduce((acc, func) => func(acc), value);
};
}
// 示例
const add = (x) => x + 2;
const multiply = (x) => x * 3;
const pipedFunction = pipe(add, multiply);
console.log(pipedFunction(5)); // 21應用場景:
- 函數式編程
- 數據流處理
11. 遞歸尾調用優(yōu)化函數 (Tail Call Optimization)
作用: 在遞歸函數中,將最后一個操作是函數調用的場景優(yōu)化,減少棧的使用。
示例:
function factorial(n, total = 1) {
if (n === 1) return total;
return factorial(n - 1, n * total); // 尾調用
}
console.log(factorial(5)); // 120應用場景:
- 深度遞歸場景(如處理樹形結構)
12. 偏應用函數 (Arity Reduction)
作用: 減少函數參數的復雜性,通過固定某些參數返回一個新函數。
示例:
function partialRight(func, ...fixedArgs) {
return function (...args) {
return func(...args, ...fixedArgs);
};
}
// 示例
function greet(greeting, name) {
return `${greeting}, ${name}`;
}
const sayHelloTo = partialRight(greet, "Hello");
console.log(sayHelloTo("Alice")); // "Hello, Alice"13. 生成器函數 (Generator Function)
作用: 用于生成一系列值,每次調用時返回一個新值,適合處理流式數據。
示例:
function* generatorFunction() {
yield 1;
yield 2;
yield 3;
}
const gen = generatorFunction();
console.log(gen.next().value); // 1
console.log(gen.next().value); // 2
console.log(gen.next().value); // 3應用場景:
- 異步流處理
- 數據生成器
14. 異步函數 (Async Function)
作用: 通過 async 和 await 關鍵字處理異步操作,簡化回調地獄。
示例:
async function fetchData() {
const response = await fetch('https://api.example.com/data');
const data = await response.json();
console.log(data);
}
fetchData();應用場景:
- 異步操作(如網絡請求、文件讀?。?/li>
15. 中間件函數 (Middleware Function)
作用: 按順序執(zhí)行一系列函數,可以動態(tài)添加功能。
示例:
function middlewarePipeline(context, middlewares) {
const executeMiddleware = (index) => {
if (index < middlewares.length) {
middlewares[index](context, () => executeMiddleware(index + 1));
}
};
executeMiddleware(0);
}
// 示例
const middlewares = [
(ctx, next) => { console.log('Middleware 1'); next(); },
(ctx, next) => { console.log('Middleware 2'); next(); },
(ctx, next) => { console.log('Middleware 3'); }
];
middlewarePipeline({}, middlewares);
// 輸出:
// Middleware 1
// Middleware 2
// Middleware 3應用場景:
- Web 框架(如 Express、Koa)
16. 動態(tài)函數 (Dynamic Function)
作用: 使用 new Function 動態(tài)創(chuàng)建函數。
示例:
const dynamicFunc = new Function('a', 'b', 'return a + b');
console.log(dynamicFunc(2, 3)); // 5應用場景:
- 動態(tài)代碼生成
- 模板引擎
17. 鏈式調用函數 (Chaining)
作用: 返回 this,允許多次調用。
示例:
class Chain {
constructor(value) {
this.value = value;
}
add(num) {
this.value += num;
return this;
}
multiply(num) {
this.value *= num;
return this;
}
print() {
console.log(this.value);
return this;
}
}
const chain = new Chain(1);
chain.add(2).multiply(3).print(); // 9應用場景:
- API 設計(如 jQuery)
18. 觀察者模式函數 (Observer)
作用: 用于監(jiān)聽對象狀態(tài)的變化并執(zhí)行回調。
示例:
class Observable {
constructor() {
this.subscribers = [];
}
subscribe(callback) {
this.subscribers.push(callback);
}
notify(data) {
this.subscribers.forEach(callback => callback(data));
}
}
// 示例
const observable = new Observable();
observable.subscribe(data => console.log('Subscriber 1:', data));
observable.subscribe(data => console.log('Subscriber 2:', data));
observable.notify('Hello, Observers!');
// 輸出:
// Subscriber 1: Hello, Observers!
// Subscriber 2: Hello, Observers!應用場景:
- 狀態(tài)管理(如 Redux、Vuex)
19. 策略模式函數 (Strategy)
作用: 根據不同的策略執(zhí)行不同的邏輯。
示例:
const strategies = {
add: (a, b) => a + b,
subtract: (a, b) => a - b,
multiply: (a, b) => a * b
};
function executeStrategy(strategy, a, b) {
return strategies[strategy](a, b);
}
console.log(executeStrategy('add', 3, 2)); // 5
console.log(executeStrategy('multiply', 3, 2)); // 6應用場景:
- 動態(tài)行為切換
- 復雜邏輯分離
20. 代理模式函數 (Proxy)
作用: 使用 Proxy 攔截對象的操作,添加額外邏輯。
示例:
const handler = {
get(target, property) {
console.log(`Getting ${property}`);
return target[property];
},
set(target, property, value) {
console.log(`Setting ${property} to ${value}`);
target[property] = value;
}
};
const obj = new Proxy({}, handler);
obj.a = 10; // Setting a to 10
console.log(obj.a); // Getting a -> 10應用場景:
- 數據綁定
- 權限控制
到此這篇關于JavaScript常見函數類型和用途的文章就介紹到這了,更多相關js 常見函數類型內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
uniapp中全局頁面掛載組件實戰(zhàn)過程(小程序)
這篇文章主要給大家介紹了關于uniapp中全局頁面掛載組件(小程序)的相關資料,文中通過實例代碼介紹的非常詳細,對大家學習或者使用uniapp具有一定的參考學習價值,需要的朋友可以參考下2022-12-12
JavaScript使用Web Worker解析CSV文件的操作方法
在處理大型 CSV 文件時,直接在主線程中解析可能會導致頁面卡頓,影響用戶體驗,使用 Web Worker 可以將計算密集型任務移到后臺線程,避免阻塞主線程,從而提升應用的響應速度,所以本文給大家介紹了JavaScript使用Web Worker解析CSV文件的操作方法,需要的朋友可以參考下2025-03-03

