Created
June 15, 2010 18:57
-
-
Save mde/439523 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
// Totally naive mixin for demonstration purposes | |
var mixInProperties = function (to, from) { | |
for (var p in from) { | |
to[p] = from[p]; | |
} | |
} | |
// Base pseudoclass | |
var InheritedCodeObj = function (id) { | |
this.id = id || '(none)'; | |
// In classical inheritance, this would be 'super' | |
this.inheritedFunction = function () { | |
console.log('Calling an inherited function on ' + this.id); | |
}; | |
}; | |
// Singleton, an instance | |
var mixinObj = new function () { | |
this.mixedInFunction = function () { | |
console.log('Calling a mixed-in function on ' + this.id); | |
}; | |
}(); | |
// Child pseudoclass for composition | |
var CompositionObj = function (parentObj) { | |
this.parentObj = parentObj; | |
this.delegatedFunction = function () { | |
console.log('Calling a function delegated to ' + | |
this.parentObj.id + '\'s child obj.'); | |
}; | |
}; | |
// Sub pseudoclass | |
var BaseObj = function (id) { | |
this.id = id; | |
this.childObj = null; | |
this.locallyDefinedFunction = function () { | |
this.inheritedFunction(); | |
this.mixedInFunction(); | |
this.childObj.delegatedFunction(); | |
console.log('Calling a locally defined function on ' + | |
this.id); | |
}; | |
}; | |
// Inherit some stuff via simple prototypal inheritance | |
BaseObj.prototype = new InheritedCodeObj(); | |
// Instantiate obj with single prototypal inheritance | |
var a = new BaseObj('a'); | |
// Mix in some stuff | |
mixInProperties(a, mixinObj); | |
// Add a child for composition/delegation | |
a.childObj = new CompositionObj(a); | |
// Call a function that demonstrates a bunch of different | |
// ways to do code reuse | |
a.locallyDefinedFunction(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment