JavaScript 中建立函式的方式極其靈活,本文整理 20 種常見模式,涵蓋函式宣告、函式運算式、物件字面量、建構函式、原型模式、模組模式、ES6 Class 等,幫助開發者根據場景選擇最適合的寫法。
function sayHello() { console.log('hello'); }
function leave() { console.log('goodbye'); }
sayHello();
var sayHello = function() { console.log('hello'); };
var leave = function() { console.log('goodbye'); };
leave();
var Action = {
sayHello: function() { console.log('hello'); },
leave: function() { console.log('goodbye'); }
};
Action.sayHello();
var Action = function() {};
Action.sayHello = function() { console.log('hello'); };
Action.leave = function() { console.log('goodbye'); };
Action.sayHello();
var Action = function() {
return {
sayHello: function() { console.log('hello'); },
leave: function() { console.log('goodbye'); }
};
};
var a = Action(); a.leave();
var Action = function() {};
Action.prototype.sayHello = function() { console.log('hello'); };
Action.prototype.leave = function() { console.log('goodbye'); };
var a = new Action(); a.sayHello();
var Action = function() {};
Action.prototype = {
sayHello: function() { console.log('hello'); },
leave: function() { console.log('goodbye'); }
};
var a = new Action(); a.leave();
var Action = function() {
this.sayHello = function() { console.log('hello'); };
this.leave = function() { console.log('goodbye'); };
};
var a = new Action(); a.leave();
Function.prototype.sayHello = function() { console.log('hello'); };
Function.prototype.leave = function() { console.log('leave'); };
var f = function() {}; f.sayHello();
Function.prototype.addMethod = function(name, fn) {
this[name] = fn;
};
var methods = function() {};
methods.addMethod('sayHello', function() { console.log('hello'); });
methods.addMethod('leave', function() { console.log('leave'); });
methods.sayHello();
Function.prototype.addMethod = function(name, fn) {
this.prototype[name] = fn;
};
var Methods = function() {};
Methods.addMethod('sayHello', function() { console.log('hello'); });
Methods.addMethod('leave', function() { console.log('leave'); });
var a = new Methods(); a.leave();
var Module = (function() {
var privateVar = 'secret';
function privateMethod() { console.log(privateVar); }
return {
publicMethod: function() { privateMethod(); }
};
})();
Module.publicMethod();
var Module = (function() {
function Constructor() { this.publicProp = 'public'; }
Constructor.prototype.publicMethod = function() { console.log(this.publicProp); };
return Constructor;
})();
var m = new Module(); m.publicMethod();
const sayHello = () => console.log('hello');
const leave = () => console.log('goodbye');
class Action {
sayHello() { console.log('hello'); }
leave() { console.log('goodbye'); }
}
const a = new Action(); a.sayHello();
class Util {
static formatDate(date) { return date.toISOString(); }
}
Util.formatDate(new Date());
class Counter {
#count = 0;
increment() { this.#count++; }
getCount() { return this.#count; }
}
function createGreeter(greeting) {
return function(name) { console.log(greeting + ', ' + name); };
}
var sayHi = createGreeter('Hi');
sayHi('Alice');
function curry(fn) {
return function curried(...args) {
if (args.length >= fn.length) return fn.apply(this, args);
return (...more) => curried.apply(this, [...args, ...more]);
};
}
const add3 = curry((a,b,c) => a+b+c);
add3(1)(2)(3); // 6
const compose = (...fns) => x => fns.reduceRight((v, f) => f(v), x);
const add1 = x => x + 1;
const double = x => x * 2;
const add1ThenDouble = compose(double, add1);
add1ThenDouble(5); // 12
| 場景 | 推薦模式 |
|---|---|
| 簡單工具函式 | 函式宣告/運算式、箭頭函式 |
| 命名空間分組 | 物件字面量、單一物件擴充 |
| 需要多實例、共享方法 | 建構函式 + 原型、ES6 Class |
| 私有狀態封裝 | 模組模式、類別私有欄位 |
| 框架/庫作者提供擴充 API | Function.prototype 擴充、addMethod 工廠 |
| 函式式資料流處理 | 高階函式、柯里化、組合 |
掌握多種函式建立模式,能讓你在不同專案規模、團隊習慣、瀏覽器支援要求下,靈活選擇最適合的程式碼組織方式,寫出更易維護、可測試、可擴充的 JavaScript 程式。