Created
December 7, 2010 16:58
-
-
Save pk/732056 to your computer and use it in GitHub Desktop.
Combining functional constructors/modules with the prototypal inheritance chain.
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
var sys = require('sys'); | |
// Namespace | |
var o2 = function O2() { | |
var o = {}; | |
// Core extensions | |
if (typeof Object.create !== 'function') { | |
Object.create = function(o) { | |
var F = function() {}; | |
F.prototype = o; | |
return new F(); | |
}; | |
} | |
// Types | |
function ConfigurationProfile(settings) { | |
var o = Object.create({}); | |
o.settings = settings; | |
var toString = function toString() { | |
throw(new Error('Override toString() in the subclass.')); | |
} | |
o.toString = toString; | |
return o; | |
}; | |
function AndroidProfile(settings) { | |
var o = Object.create(new ConfigurationProfile(settings)); | |
var toString = function toString() { return 'Android'; } | |
// Public interface | |
o.toString = toString; | |
return o; | |
}; | |
function IPhoneProfile(settings) { | |
var o = Object.create(new ConfigurationProfile(settings)); | |
var toString = function toString() { return 'iPhone'; } | |
// Public interface | |
o.toString = toString; | |
return o; | |
}; | |
// Export Types | |
o.AndroidProfile = AndroidProfile; | |
o.IPhoneProfile = IPhoneProfile; | |
return o; | |
}(); | |
var profile = o2.AndroidProfile({msisdn: 12345678}); | |
sys.puts(sys.inspect(profile)); | |
sys.puts(sys.inspect(profile.settings)); | |
sys.puts(sys.inspect(profile.toString())); //=> Android | |
var profile = o2.IPhoneProfile({msisdn: 87654321}); | |
sys.puts(sys.inspect(profile)); | |
sys.puts(sys.inspect(profile.settings)); | |
sys.puts(sys.inspect(profile.toString())); //=> iPhone |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment