I have defined my class like so:
function Slot(slot, maxSpeed, timer) {
this.slot = slot;
this.speed = 0;
this.maxSpeed = maxSpeed;
this.timer = timer;
this.interval = null;
this.go = function() {
var $slot = $(this.slot);
console.log(this.slot);
$slot.addClass('motion');
$slot.spStart();
this.interval = window.setInterval(function() {
var step = Math.floor(Math.random() * ((this.speed / 100) * 25)) + 1;
if (this.speed < (this.maxSpeed / 2)) {
this.speed += step;
}
if (this.speed >= (this.maxSpeed / 2)) {
this.speed -= step;
}
console.log(this.slot);
$slot.spSpeed(this.speed);
}, timer);
};
$(this.slot).pan({ fps: '30', dir: 'down' });
$(this.slot).spStop();
}
The first console.log returns the expected value, but once I get into the setInterval function all variables (this.slot, this.speed) are all undefined? Even though I am still within their scope…
Scoping is a bit weird to get used to in Javascript, even weirder when you start using setInterval and setTimeout.
In your case, the this that’s inside the interval is referring to the anonymous function itself. You can either assign ‘this’ to another variable outside the anonymous function:
or you can call a function on the object in the interval step: