Skip to content

Instantly share code, notes, and snippets.

@evandrojr
Created February 11, 2017 21:37
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save evandrojr/2ff91aca0c5a8c9f972d2937c40276cc to your computer and use it in GitHub Desktop.
Save evandrojr/2ff91aca0c5a8c9f972d2937c40276cc to your computer and use it in GitHub Desktop.
Mixin example in JS
// vastly simplified `mixin(..)` example:
function mixin( sourceObj, targetObj ) {
for (var key in sourceObj) {
// only copy if not already present
if (!(key in targetObj)) {
targetObj[key] = sourceObj[key];
}
}
return targetObj;
}
var Engine = {
engines: 1,
ignition: function() {
console.log( "Turning on my engine." );
},
};
var SteeringWheel = {
wheels: 1,
drive: function() {
this.ignition();
console.log( "Steering and moving forward!" );
}
};
var Car = mixin(Engine, {});
var Car = mixin(SteeringWheel, Car);
var Car = mixin( Car, {
wheels: 4,
drive: function() {
SteeringWheel.drive.call( this );
console.log( "Rolling on all " + this.wheels + " wheels!" );
}
} );
c = Car;
console.log(c.wheels)
c.drive()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment