- [Narrator] When you want to extend a class
create a new one you can only extend one at a time
and in most cases that will be enough
but sometimes you might need to extend more than one class
into a single class, this is where mixins are useful.
As for the Gang of Four this is one pattern where we favor
composition over inheritance.
With extends we inherit from the parent class
with mixins we compose into a new class.
Some use cases could be where you implement specific methods
as part of a class and others into another.
And then when to create a new class
which will include all these methods
mixins would be your solution to do so.
There are multiple ways to add mixins into your class
but let me demonstrate a simple way of doing so.
Also be wary of using mixins
in your everyday life as a developer
as they sometimes add complexity
and in some communities, like React, are frowned upon.
This is, in a way, academic,
so you understand what they are, but use them with caution.
So let's go to Code and let's add a mixin,
so, let's go to the top of our file here
where you see class car at line one,
and let's create a mixin, so let mixin
equals and then create an object which will have a function.
And let's create made in.
And then that function will simply return something
in our console log, so let's do
this car
was made
in year 2019.
And then we'll add that mixin to a prototype
so let's go and do this again
this is a lot of verbose code to do something very simple
but it's how it works
and this is why it's frowned upon in the community,
so, again, use with caution,
so, let's go and do a proto
and then pass mixin
and then we'll use the function inside the new function here
in our prototype with the word super.
Now we're ready to use it.
Alright so let's assign that mixin
into our car or the SUV here.
So again what we're doing here
is not inheritance but composition.
So here we're going to assign...
Let me just type a note here, assign mixin,
and then do an object dot assign
to this in car mixin.
Now we have the mixin assigned to the SUV
so now we can use it in a console log,
so again, let's do a console log,
and what we'll do is cx5
and the function from the mixin, which is made in,
so if you remember here we created the made in function
inside of our car mixin,
which we passed to the SUV class here
by assign it to the object,
so now we have it available and we can actually run it here.
So the function is going to return to us a console log,
this car was made in year 2019.
So let's save all this
and go back to our Sandbox, and we have,
this car was made in year 2019.
So this is how you view mixins inside of a class.
So again this is to allow you to compose
different things into your class
and not inherit from a previous class by extending.
Something that I would use with caution
because it's frowned upon
it's not something that everybody likes to use,
but, at least it's good to be aware of what it is.