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
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
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.