Jump to content

closure issue


purencool

Recommended Posts

Hi php freaks

I have been using prototype in javascript and found that to get setTimeout to call another

method I need to add a closure. But I can't get it work can anyone help.  I am new to closures.

            function fadingImagesIn(idArray,intNum){
                //this is the constructor for the fading images
                this.idArray= idArray;
                this.intNum = intNum;

            }
            fadingImagesIn.prototype.fadeIn = function(id)
            {
                var element=document.getElementById(id);
                if (element.timer) window.clearTimeout(element.timer);
                var startMS = (new Date()).getTime();
                element.timer = window.setTimeout("this.changeOpacity('" + id + "',1000," + startMS + ",0,100)",1);
            }

            fadingImagesIn.prototype.timer =function(){
                var x = this.intNum;
                x++;
                alert (this.idArray[0]);
                for (i=0;i<=x;i++)
                {
                    if(i == 0){
                        //Allows page to load
                        setTimeout ( "",  1000 );

                    }else{
                        //Makes the images visible.
                        //every second goes to timer and then come back
                        // setTimeout("alert(hi)",1000);

                        setTimeout(function(){this.fadeIn('logoDiv1')},1000);


                    }

                }
            }

            // This creates the object
            var imagefading = new fadingImagesIn(new Array('logoDiv1','logoDiv2','logoDiv3'), 2);

            //-->

Link to comment
https://forums.phpfreaks.com/topic/188408-closure-issue/
Share on other sites

As you can see 'this' does not refer to the fadingImagesIn object, resulting in that error.  To get the correct scope, you can create a variable referencing the desired 'this' and use that within the anonymous function in setTimeout, like:

 

fadingImagesIn.prototype.timer =function(){
    var self = this;
    // ...
    setTimeout(function(){self.fadeIn('logoDiv1')},1000);
    // ...
}

Link to comment
https://forums.phpfreaks.com/topic/188408-closure-issue/#findComment-994755
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.