Skip to content

Instantly share code, notes, and snippets.

@Kcko
Last active June 23, 2025 10:54
Show Gist options
  • Save Kcko/af391e6feeb5c5bf09271d301f7db266 to your computer and use it in GitHub Desktop.
Save Kcko/af391e6feeb5c5bf09271d301f7db266 to your computer and use it in GitHub Desktop.
// 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);
}
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()
// 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);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment