If I understand correctly mixins can have state, whereas traits, as a subset of mixins, cannot.
How can we implement stateful mixins in JavaScript.
I can think of two ways - partial application and via closure. Are there any others?
For example:
var foo, bar, bam, closedOver = 'c';
foo = { a: function() { console.log('a'); } };
bar = { b: (function(x) { console.log('b: ' + x); }.bind(this, '1')) };
bam = { c: function() { console.log(closedOver); } };
function mix(original, ...objs) {
objs.forEach(o => {
Object.keys(o).forEach(k => {
original[k] = o[k];
});
});
}
mix(foo, bar, bam);
console.log(foo.a); // a
console.log(foo.b); // b: 1
console.log(foo.c); // c
Edit: I just realised that of course functions are objects in JavaScript and can have arbitrary state associated with them. I would like to know the answer to an ancillary question - do mixins have to be functions?