Here are the code:
var
shuriken = {
hit:function(who){alert("pierced the "+who+" armor");}
},
sword = {
hit:function(who){alert("Chopped the "+who+" in half");}
};
function Samurai(weapon){
return {
Attack:function(who){
weapon.hit(who);
}
}
}
container.register("samurai",Samurai);
var warrior1 = container.byConstructor("samurai",shuriken),
warrior2 = container.byConstructor("samurai",sword);
warrior1.Attack("The evildoers");
warrior2.Attack("The evildoers");
So simple, So clear!
2 commenti:
I like it. :) Nice idea for IoC in JavaScript, also!
I'm glad you liked your example in javascript ;D
I like the way Ninject use the attributes for injection declaration, in javascript this is not possible.
I think that "IoC by hand" is the best way to achieve IoC in js , altough is possible to use XML(or json) like I've done here (I keep it simple and way incomplete because doing so i avoided explaination ;D ):
http://houseofhackers.ning.com/group/jsninjas/forum/topic/show?id=2092781%3ATopic%3A42332
using xml/json can be good for plugins
implementation in javascript so IoC can be useful,
even if in js there is not a real coupling
Posta un commento