I have been toying around with OOP, and figured it would be a good exercise to create a class that animated the bg of an object.
during this process ran in to a curious behaviour:
Class C , creates/clones an enlement… setting it to a user defined dimension , assigns it a a bg sprite… the foolowing code, also part of the class serves to animate this bg.
C.prototype.anim = function( ){
if (this.seqCt < this.seqL-1 ){this.seqCt++}
else{this.seqCt = 0;}
this.el.style.backgroundPositionX=(this.seqX+(this.seqCt * this.seqXp))+'px';
this.el.style.backgroundPositionY=(this.seqY+ (this.seqCt * this.seqYp))+'px';
}
C.prototype.runSeq = function(self){
self.a = setInterval( function(){self.anim()},self.int) ;
}
This woks perfectly… but I came around this solution after much trial an error, and am no tparticularly pleased that the code must be called like this:
obj.runSeq(obj);
I mean why must I pass the object to itself? isn’t that what ‘this’ is for?
In my original code differed ONLY thus:
C.prototype.runSeq = function(){
self=this;
self.a = setInterval( function(){self.anim()},self.int) ;
}
so I could do : obj.runSeq( );
the problem was if I had multiple instances , then only the last instance was actually running the runSeq method. This was really weird since,all other properties, were unique to each instance and did not affect each other.
Please pardon that my knowledge of OOP is mostly from PHP, but why would have needed to pass the instance itself to a function that part of the class definition? Shouldn’t ‘this’ represent the instance in this context and not the ‘class’?