Instantiating .this?

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.seqXp))+'px'; (this.seqCt * this.seqYp))+'px';
 			C.prototype.runSeq = function(self){
  				self.a = setInterval( function(){self.anim()}, ;

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:


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.a = setInterval( function(){self.anim()}, ;

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’?

You’re gonna slap yourself for this one. :wink:

You’re missing “var”. var self=this; Otherwise, “self” is global, and all instances would reference the same “self” variable.

Also, JSHint is your friend. JavaScript is a language where it’s easy to make small mistakes such as this. JSHint will catch a lot of those mistakes for you.

holly … yeah. am going to device a self kicking mech next!

thanks for the link, bookmarking it now!!

Just to answer this part of the question more fully, sometimes people code like that when they are using TDD techniques to test the code. It allows the code be tested in isolation to a larger degree.
There are ways though of doing TDD while allowing the execution context of the this keyword to remain though.

Another reason why such code structures are seen are due to copying code from one language to another.

I’m glad that you are spotting such issues, because making good use of a language’s features without losing the ability to maintain a testable code base, is a good practice to maintain.