How to make that in the animate self function refer to the Animation instance, and not to the window, without resorting to cloning the function inside the Animation?

var Animation = function (frameCount_) { var self = this; this.image = image_; this.frameCount = frameCount_; this.i = 1; this.x = 0; this.y = 0; this.animateTimer = 0; this.start(); } Animation.prototype.start = function () { clearInterval(this.animateTimer); setInterval(this.animate, 50); } Animation.prototype.stop = function () { clearInterval(this.animateTimer); } Animation.prototype.animate = function () { if (self.i < self.frameCount) { self.i++; } else { self.i = 1; } self.x = (self.i - 1) * 50; } 

    2 answers 2

    1. not Animation.this , but Animation.prototype
    2. self = this in the second line does not make sense
    3. in the animate self function is not initialized, I assume here should be

    On the issue:

     Animation.prototype.start = function () { var me = this; clearInterval(me.animateTimer); me.animateTimer = setInterval(function(){me.animate()}, 50); } Animation.prototype.stop = function () { clearInterval(this.animateTimer); this.animateTimer = null; } 
    • Yes, sorry, there was a prototype, I forgot to fix it when copying. The meaning of the second line, if I had the animate function right inside the constructor, then by closing it would be available when the timer called this function. If the execution context of the prototype were inside the object, then the self variable for the animate function would be initialized. If you use this in animate, then it refers to window - asci

    Most likely it’s still not self but this , but probably so:

     Animation.this.animate = function () { if (this.i < self.frameCount) { this.i++; } else { this.i = 1; } this.x = (this.i - 1) * 50; }; Animation.this.start = function () { clearInterval(this.animateTimer); with (this) { // setInterval(animate, 50); // тут была ошибка // Строчка ниже работает правильно animateTimer = setInterval(function () { animate(); }, 50); } }; 

    But I would rewrite the whole thing as a class

    UPDATE - Fixed version, if the function is used directly (without a wrapper), the context is lost

    • And what really works? - aachurin
    • Slightly different, but it works: jsfiddle.net/chernomyrdin/KRpUq/1 fixed the answer - chernomyrdin
    • one
      Well, fundamentally different - aachurin