On gists
Advanced Patterns: Mixins and Composition
•
JavaScript-OOP
JavaScript
composition.js
Raw
#
// https://medium.com/@genildocs/mastering-object-oriented-programming-in-javascript-from-zero-to-hero-c718c3182eba
// Mixin for logging functionality
const LoggerMixin = {
log(message) {
console.log(`[${this.constructor.name}] ${message}`);
},
logError(error) {
console.error(`[${this.constructor.name}] ERROR: ${error}`);
}
};
// Mixin for validation
const ValidatorMixin = {
validate(data, rules) {
for (const [field, rule] of Object.entries(rules)) {
if (!rule(data[field])) {
return { valid: false, field };
}
}
return { valid: true };
}
};
class UserService {
constructor() {
// Apply mixins
Object.assign(this, LoggerMixin, ValidatorMixin);
}
composition2.js
Raw
#
let sayHiMixin = {
sayHi() {
alert(`Hello ${this.name}`);
}
}
let sayByeMixin = {
sayBye() {
alert(`Bye ${this.name}`);
}
}
class User {
constructor(name) {
this.name = name;
}
}
// copy the methods
Object.assign(User.prototype, sayHiMixin);
Object.assign(User.prototype, sayByeMixin);
const user = new User("Dude")
user.sayHi()
user.sayBye()
composition3.js
Raw
#
// Instead of deep inheritance hierarchies
class DatabaseLogger extends Logger extends BaseService {}
// Use composition
class UserService {
constructor(logger, database) {
this.logger = logger;
this.database = database;
}
createUser(data) {
this.logger.info("Creating user");
return this.database.save(data);
}
}