Surrogate classes in Troop
Demonstrates use of surrogate classes for instantiating derived classes through base class Other resources: http://jsfiddle.net/danstocker/n5jze/ http://jsfiddle.net/danstocker/YR374/ https://github.com/production-minds/troop
by Dan Stocker
HTML
<script src="https://dl.dropbox.com/u/9258903/JavaScript/dessert-0.3.2.js"></script>
<script src="https://dl.dropbox.com/u/9258903/JavaScript/troop-0.6.1.js"></script>
JavaScript
// namespace
var ns = {};
// normal horse
ns.Horse = troop.Base.extend()
// surrogate class for when height below 5 is given in ctr arg
.addSurrogate(ns, 'Pony', function (height) {
// surrogate class is selected on instantiation
// when evaluator function returns true
return height < 5;
})
.addMethods({
// dummy ctr
init: function (height) {}
});
// pony is a kind of horse
ns.Pony = ns.Horse.extend()
.addMethods({
// dummy ctr
init: function (height) {}
});
// instantiating horse and pony through base class (ns.Horse)
var myHorse = ns.Horse.create(10),
myPony = ns.Horse.create(3);
$('body').append(
"tall horse is " + (myHorse.isA(ns.Pony) ? "Pony" : "Horse") +
"<br/>short horse is " + (myPony.isA(ns.Pony) ? "Pony" : "Horse")
);