DEV Community

Ravina Deogadkar
Ravina Deogadkar

Posted on • Edited on

4 1

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!

SurveyJS custom survey software

JavaScript UI Libraries for Surveys and Forms

SurveyJS lets you build a JSON-based form management system that integrates with any backend, giving you full control over your data and no user limits. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more.

Learn more

Top comments (0)

Cloudinary image

Optimize, customize, deliver, manage and analyze your images.

Remove background in all your web images at the same time, use outpainting to expand images with matching content, remove objects via open-set object detection and fill, recolor, crop, resize... Discover these and hundreds more ways to manage your web images and videos on a scale.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay