Created
November 23, 2011 23:32
-
-
Save JCallicoat/1390245 to your computer and use it in GitHub Desktop.
Mixin objects in Javascript
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
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