Skip to content

Instantly share code, notes, and snippets.

@JCallicoat
Created November 23, 2011 23:32
Show Gist options
  • Save JCallicoat/1390245 to your computer and use it in GitHub Desktop.
Save JCallicoat/1390245 to your computer and use it in GitHub Desktop.
Mixin objects in Javascript
Object.prototype.mixin = function(module, overwrite)
{
for (var property in module)
{
if (overwrite || !this.hasOwnProperty(property))
{
this[property] = module[property];
}
}
}
var CoolGuy = {
shades: function()
{
print("YEEEAHHHHHHHH!!!!!");
}
}
// object mixin -- all new instances of Kenny get property
var Kenny = function(){};
Kenny.prototype.mixin(CoolGuy);
var kenneh = new Kenny();
kenneh.shades();
var kennbe = new Kenny();
kennbe.shades();
// instance mixin -- only this instance of Danny gets property
var Danny = function(){};
var dwitt = new Danny();
dwitt.mixin(CoolGuy);
dwitt.shades();
var weditt = new Danny();
weditt.shades(); // oops, no shades property
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment