Created
February 11, 2017 21:37
-
-
Save evandrojr/2ff91aca0c5a8c9f972d2937c40276cc to your computer and use it in GitHub Desktop.
Mixin example in JS
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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