Understanding and Applying the Strategy Pattern in JavaScript
This article explains the Strategy design pattern, demonstrates its refactoring in JavaScript through bonus‑calculation and Axios adapter examples, and shows how applying the pattern improves code clarity, extensibility, and maintainability in frontend development.
The Strategy pattern is defined as a way to encapsulate a family of algorithms, making them interchangeable. It is useful when business logic varies across different scenarios, such as calculating year‑end bonuses based on performance levels.
Original code often uses multiple if‑else statements, leading to problems like excessive conditional logic, poor extensibility (violating the Open/Closed Principle), and low algorithm reuse.
var calculateBouns = function (performanceLevel, salary) {
if (performanceLevel === 'S') {
return salary * 4;
}
if (performanceLevel === 'A') {
return salary * 3;
}
if (performanceLevel === 'B') {
return salary * 2;
}
}
calculateBouns('S', 20000);Refactoring with the Strategy pattern separates the algorithm implementation from its usage. Each performance level becomes a separate strategy object with its own calculate method, and a context object delegates the calculation to the selected strategy.
// Performance algorithms
var performanceS = function() {};
performanceS.prototype.calculate = function (salary) { return salary * 4; };
var performanceA = function() {};
performanceA.prototype.calculate = function (salary) { return salary * 3; };
var performanceB = function() {};
performanceB.prototype.calculate = function (salary) { return salary * 2; };
// Bonus context
var Bouns = function () {
this.salary = null;
this.strategy = null;
};
Bouns.prototype.setSalary = function (salary) { this.salary = salary; };
Bouns.prototype.setStrategy = function (strategy) { this.strategy = strategy; };
Bouns.prototype.getBouns = function () { return this.strategy.calculate(this.salary); };
var bouns = new Bouns();
bouns.setSalary(1000);
bouns.setStrategy(new performanceS());
bouns.getBouns();A more concise JavaScript version treats strategies as plain functions stored in an object, allowing direct lookup by performance level.
var strategies = {
'S': function (salary) { return salary * 4; },
'A': function (salary) { return salary * 3; },
'B': function (salary) { return salary * 2; }
};
var calculateBouns = function (level, salary) { return strategies[level](salary); };
calculateBouns('A', 2000);The article also examines how Axios implements the Strategy pattern internally. Depending on the runtime environment, Axios selects either an XHR adapter for browsers or an HTTP adapter for Node, both exposing a unified Promise‑based API.
function getDefaultAdapter() {
var adapter;
if (typeof XMLHttpRequest !== 'undefined') {
// For browsers use XHR adapter
adapter = require('./adapters/xhr');
} else if (typeof process !== 'undefined' && Object.prototype.toString.call(process) === '[object process]') {
// For node use HTTP adapter
adapter = require('./adapters/http');
}
return adapter;
}Real‑world usage is illustrated with a VIP client example, where different request implementations are encapsulated in separate classes and selected at runtime, eliminating repetitive if‑else checks.
class VIPClient {
constructor(clientId) { this.clientId = clientId; }
getList() { return getVIPList(this.id); }
getDetail() { return getVIPDetail(this.id); }
}
class Client {
constructor(clientId) { this.clientId = clientId; }
getList() { return getList(this.id); }
getDetail() { return getDetail(this.id); }
}
let client;
if (vip) {
client = new VIPClient(id);
} else {
client = new Client(id);
}
const list = await client.getList();In summary, the Strategy pattern, though simple, provides a powerful way to organize varying business logic, improve code readability, and facilitate future extensions, especially in frontend development scenarios such as request handling, animation effects, and validation rules.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Rare Earth Juejin Tech Community
Juejin, a tech community that helps developers grow.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
