The same code in several places is the pain. Today I will say a few words about repeated parts of classes. Coders had invented a solution of this problem a long time ago: you can move similar methods and properties to a common parent class or, if you don’t have one, you can use mixins. There are many implementations of this pattern in JavaScript, but I want to review the case when a mixin is placed to the prototype chain.
At one point of development process, similar functionality is required in both the child classes. A dull copy-paste will look on the scheme like that
It’s very often, the functionality has nothing to do with the base classes, therefore, to move it to another parent class is improperly and inconvenient at least. So let’s place it to a special entity - mixin. In the context of the language mixin can be a simple object.
Now we are about to most interesting question, that is “What’s the right way to mix our mixin to the classes?” From a personal perspective I can assert that the best way is creation of temporary classes with the mixin as a prototype and insertion them into the prototype chains.
Picture of Idea
Let’s start with visual presentation of the problem. Consider we have two base classes and two child classes inherited respectively.At one point of development process, similar functionality is required in both the child classes. A dull copy-paste will look on the scheme like that
It’s very often, the functionality has nothing to do with the base classes, therefore, to move it to another parent class is improperly and inconvenient at least. So let’s place it to a special entity - mixin. In the context of the language mixin can be a simple object.
Now we are about to most interesting question, that is “What’s the right way to mix our mixin to the classes?” From a personal perspective I can assert that the best way is creation of temporary classes with the mixin as a prototype and insertion them into the prototype chains.