0

Hi I'm trying to create an object in jQuery and everything is working fine but somehow I cannot pass some necessary properties beyond the setInterval function bc when I test it it always pops "undefined". Here is the draft code of that I have.

Thanks in advance!!

   function MyFunction(var1){
     this.var = var1;
     this.var2 = 2;
     this.pause = 3000;
     this.slideOn();
    }

    MyFunction.prototype.slideOn = function(){ 

      alert(this.var); //alerts the value

      setInterval(function(){ //doesnt work and it alerts "undefined"

      alert(this.var2),1000,function(){} 

      },this.pause // works again with no hassle

    };

1 Answers1

1

When you use "this" inside some callback function, it uses function scoped "this". So, try setting an "outer this":

function MyFunction(var1){
 this.var = var1;
 this.var2 = 2;
 this.pause = 3000;
 this.slideOn();
}

MyFunction.prototype.slideOn = function(){ 
  var _this = this;
  alert(_this.var); //alerts the value

  setInterval(function(){ //doesnt work and it alerts "undefined"

  alert(_this.var2),1000,function(){}; //100 and function are senseless

  },_this.pause); // works again with no hassle

};
Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151
Matheus Martins
  • 1,012
  • 7
  • 7