javascript - variable is set to undefined in function -
this question has answer here:
i trying create slide show load next slide before current 1 done. have 2 prototypes this. 1 showing current slide , 1 loading next slide.
it worked fine until put settimeout()
delay between slides. nextslide()
function calling after settimeout()
this.nextslide
undefined if it's loaded , added this.nextslide
in loadnextslide()
.
$(document).ready(function(){ //set width , height of canvas var width = $(document).width(); var height = $(document).height(); $("#mkslide").css({"width":width+"px","height":height+"px"}); slideshow = new slideshow(width, height, "2d"); slideshow.loadnextslide(null); slideshow.nextslide(); }); function slideshow(canvaswidth, canvasheight, dimension){ //creating slideshow } slideshow.prototype.loadnextslide = function(currentslidenumber){ var data = $.parsejson($.ajax({ type: "post", url: "/cms/php/request.php", datatype: "json", data: {slidenumber : currentslidenumber}, async: false }).responsetext); this.nextslide = data; alert(this.nextslide.id); } slideshow.prototype.nextslide = function(){ alert(this.nextslide.id); this.currentslide = this.nextslide; //swap next slide. if(beginswithhttp(this.currentslide.data)){ this.image.src = this.currentslide.data; } else{ this.image.src = "http://" + this.currentslide.data; //set current slide. } this.loadnextslide(this.currentslide.id); //preload next slide window.settimeout(this.nextslide,this.currentslide.duration * 1000);//wait x seconds before swapping }
add bind(this)
follows:
window.settimeout(this.nextslide.bind(this),this.currentslide.duration * 1000);
settimeout
schedules function execute later, , @ time context in executed global object (window
), instead of object. , context this
refers to. bind method creates new reference method override behaviour , run this
set pass bind
, independent of context called from.
an alternative, less elegant solution pass settimeout
anonymous function in method called explicitly object's context:
var = this; // keep reference object window.settimeout(function () { that.nextslide(); // use reference object }, this.currentslide.duration * 1000);
Comments
Post a Comment