[Design Pattern] Mixin pattern in Javascript

Problem to Solve

Share functionality between classes without using inheritance.

Solution

Create a class containing methods that can be used by other classes and apply it to multiple classes.

 

Code

let sayHiMixin = {
  sayHi() {alert(`Hi, ${this.name}`)}
}

class User {
   name;
}

Object.assign(User.prototype, sayHiMixin);

Then all the instance of Userwill be able to call the sayHimethod.

posted @ 2024-08-14 14:48  Zhentiw  阅读(4)  评论(0编辑  收藏  举报