DEV Community

Ravina Deogadkar
Ravina Deogadkar

Posted on • Updated on

JavaScript : Mixins

Hi everyone!... Hope everything is well at your side. Lately I was working with JavaScript objects and came across a scenario to inherit from two different classes. But JavaScript allows to extend from only one class. There will be only one [[prototype]] for an object. So I was in a deadlock to have my class inherit properties from both the object. Let's look at the problem statement first..

Problem Statement

I have User base class and a extended Admin class having additional functionality along with the base class functionality. Admin is responsible for creating Group, deleting and removing user.
User class

Now I have User class holding base methods and Admin class that inherits base class methods as well as it has his own method to setThemes and removeUser methods.

Admin class

The Group class will have all the methods to create, update, delete group and remove user from group.

Group class

Now Admin class needs access to Group class methods to create, update or delete group and remove user from group. Admin cannot extend Group class.

Proposed Solution

We can create Group class and assign all of its methods to Admin prototype. This way Admin will have access to all of the methods of Group class without inheriting it, this method is what called as Mixin.

Mixin Class

and this could be used as

Mixin class uses

createGroup, updateGroup, deleteGroup and removeUser methods of Group class got copied to Admin class and we can use them using admin object.
Now if I want inherit another class from User class suppose GroupLead who also need access to Group class methods I can make use of mixin to use those methods without duplicating them in GroupLead class.

Advantages

  • Function Reuse
  • Reduce code duplication

Disadvantage

  • Mixed-in Function can led to confusion over the source of methods.

That's all for today until then, Happy Coding!

Top comments (0)