Skip to content

Instantly share code, notes, and snippets.

@denniskuczynski
Last active September 30, 2017 15:48
Show Gist options
  • Save denniskuczynski/445dcdf4f925b27caafd to your computer and use it in GitHub Desktop.
Save denniskuczynski/445dcdf4f925b27caafd to your computer and use it in GitHub Desktop.
ES6 Mixins
// Mixins with just Object.assign
// (Could have used _.extend without ES6)
(function() {
"use strict";
// Define 3 Mixins Related to Vehicles
var HasWheels = {
wheelCount: 4, // default to 4 wheels
getWheelCount: function() {
return this.wheelCount;
}
};
var HasHorn = {
hornSound: 'BEEP!', // default to beep
getHornSound: function() {
return this.hornSound;
}
};
var HasBasket = {
basketCapacity: 0.0, // default to empty
getBasketCapacity: function() {
return this.basketCapacity;
},
addToBasket: function(item, amount) {
this.getItemsInBasket().push(item);
this.basketCapacity += amount;
},
getItemsInBasket: function() {
if (!this.items) {
this.items = [];
}
return this.items;
}
};
// Define Car and Bike Types
var Car = Object.assign({
model: 'Ford Focus', // default to Dennis' Car
getModel: function() {
return this.model;
}
}, HasWheels, HasHorn);
var HasBikeHorn = Object.assign({}, HasHorn, { hornSound: 'HONK!' });
var Bike = Object.assign({}, HasWheels, { wheelCount: 2 }, HasBikeHorn, HasBasket);
// Create instances
var car = Object.create(Car);
console.log('CAR');
console.log('---');
console.log(car.getModel());
console.log(car.getHornSound());
console.log(car.getWheelCount());
console.log('BIKE');
console.log('----');
var bike = Object.create(Bike);
console.log(bike.getHornSound());
console.log(bike.getWheelCount());
bike.addToBasket('newspapers', 0.5);
console.log(bike.getItemsInBasket());
console.log(bike.getBasketCapacity());
// Let's use a class to represent a Truck
var CarClass = function() {};
CarClass.prototype = Car;
Object.assign(CarClass.prototype, HasBasket);
// Mixing in with classes needs wrapping, because you need to mix into the prototype not the constructor
// This could be wrapped in a mix() function
class Truck extends CarClass {
// Truck is just a car with a basket
}
console.log('TRUCK');
console.log('-----');
var truck = new Truck();
console.log(truck.getHornSound());
console.log(truck.getWheelCount());
truck.addToBasket('lumber', 0.8);
console.log(truck.getItemsInBasket());
console.log(truck.getBasketCapacity());
})();
$ babel-node mixins
CAR
---
BEEP!
4
BIKE
----
HONK!
2
[ 'newspapers' ]
0.5
TRUCK
-----
BEEP!
4
[ 'lumber' ]
0.8
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment