0

i'm trying build slideshow function with OOP literal way.

so, this is my code :

"use strict";

var slideshow = {

    elSet   : $(".slideshow"),
    elCount : indexCount(".dealList"),
    elWidth : width(".dealList"),
    elNo    : 1,
    next    : function() {

                if (this.elNo < this.elCount) {
                    console.log(this.elSet);
                    this.elNo += 1;
                    this.elSet.style.transform = "translateX(-" + this.elWidth * this.elNo + "px)";
                }
                else {
                    console.log(this.elSet);
                    this.elNo = 1;
                    this.elSet.style.transform = "translateX(-" + this.elWidth * this.elNo + "px)";
                }
    },
    initial : function() {

                var loop = setInterval(this.next, 5000);
    }

}

slideshow.initial();

the problem occure in browser console :

  1. out of memory
  2. console.log return undefined

it is possible the problem occure because of this keyword?

what's wrong with my code?

Ching Ching
  • 1,029
  • 4
  • 19
  • 33

1 Answers1

5

The callback of the setInterval() when executed is bound to the global object and not your object. You can, however, bind it to your object by using this code instead:

initial : function() {
  var loop = setInterval(this.next.bind( this ), 5000);
}
Sirko
  • 72,589
  • 19
  • 149
  • 183
  • Why not use your JS dupehammer to point this to the canonical Q&A? – James Thorpe Dec 29 '15 at 13:50
  • @JamesThorpe Usually I'm too lazy to find the canonical answer and just writing 5 lines is faster. – Sirko Dec 29 '15 at 13:53
  • Haha... fair enough... I have a few bookmarks as there are [a](http://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example) [few](http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call) [questions](http://stackoverflow.com/questions/14028959/why-does-jquery-or-a-dom-method-such-as-getelementbyid-not-find-the-element) [that](http://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron) keep being asked...! – James Thorpe Dec 29 '15 at 13:55
  • thanks Sirko for your method, i appreciate it – Ching Ching Dec 29 '15 at 13:55
  • anyway Sirko, is there any alternative way to solve this problem, like using var that = this? – Ching Ching Dec 29 '15 at 14:14
  • @ChingChing something like this would work also: `initial: function(){ var self = this, loop = setInterval( function(){ self.next(); }, 5000 ); }`. – Sirko Dec 29 '15 at 14:38
  • thanks Sirko, i will use this method. it seems like more relevant. thanks :) – Ching Ching Dec 29 '15 at 15:10