javascript - Module/prototype and multiple instances -


i'm trying grip on "oop" javascript techniques, , began writing small test application today. basically, it's game loop , on each update coordinates increased html element moves.

the problem want able run more 1 instance of app, , therefore i'm trying store instance data in this, saved in constructor , exec() method not available in private update() method. seems officer, problem?

var jsloth = (function () {     var jsloth = function () {         var sloth = document.createelement('div');         var attr = document.createattribute('class');         attr.value = 'sloth';         sloth.setattributenode(attr);         this.sloth = document.getelementsbytagname('body')[0].appendchild(sloth);     };      var exec = function () {         this.x = 0;         this.y = 0;         var = this;         setinterval(function () {             that.update();         }, 1000/10);     };      var update = function () {         this.x++;         this.y++;         this.sloth.style.left = this.x + 'px';         this.sloth.style.bottom = this.y + 'px';     };      jsloth.prototype.constructor = jsloth;     jsloth.prototype.exec = exec;     jsloth.prototype.update = update;      return jsloth; })();  var sloth1 = new jsloth(); sloth1.exec(); 

edit: updated code working solution!

you've not added update prototype. value of this in method window object.

change call this:

update(); 

to this:

update.call(this); 

or add update .prototype:

jsloth.prototype.update = update; 

and use:

this.update(); 

but if you're going call update() setinterval(), you'll need ensure proper this value.

to that, can pass anonymous function, , keep reference outer this value in variable.

var exec = function () {     this.x = 0;     this.y = 0;     var = this;     setinterval(function() {         that.update();       //update.call(that); // if didn't add update() .prototype     }, 1000/10); }; 

Comments

Popular posts from this blog

Perl - how to grep a block of text from a file -

delphi - How to remove all the grips on a coolbar if I have several coolbands? -

javascript - Animating array of divs; only the final element is modified -