Last active
June 23, 2025 10:54
-
-
Save Kcko/af391e6feeb5c5bf09271d301f7db266 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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); | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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