Totally. Awesome.
http://michaelpaulus.com/gallery/v/character-Skeletons/
Assigned as homework in middleschool:
http://michaelpaulus.com/gallery/v/character-Skeletons/album02
Prototypal inheritance
Once again, I got doing inheritance in Javascript wrong. I was deceived, as the language designers intended, into believing that classes and objects were separate entities like in Java or C++. Nope! No such thing as classes.
Douglas Crockford gives this solution (though I added the super atribute) for getting rid of new and using the OOP inherent in Javascript as naturally as possible:
Class={
beget:function(){
var F=function(self){return function(){
this.super=self;
}}(this);
F.prototype=this;
return new F();
}};
Now you create new objects by saying
A=Class.beget();
A.init=function(args){
// put arg-dependent definitions here
// "this" works just fine.
}
What if you want two instances of a class? YOU STOP THINKING THAT WAY! In javascript, what you want to do is get two derived objects from a common ancestor:
B=A.beget(); C=A.beget();
This way, you get inheritance and polymorphism:
A.x=1; A.y=3;
A.f=function(){return this.x};
B.x=2;
alert(B.x); // 2
alert(B.super.x); // 1
alert(C.x); // 1
alert(B.y); // 3
alert(B.f()); // 2
leave a comment