Solved

Javascript Recursive Object Method

Posted on 2006-12-01
4
208 Views
Last Modified: 2008-02-01
Dear Experts,

My object "RotatingBanner" has one function "RotateBanner()".

These are declared below:
******************************************
function RotateBanner()
{
      if (!document.images) return;

      if (this.nowIsFirstPass == 1)
      {
            this.nowIsFirstPass = 0;
      }
      else
      {
            if (this.nowRotationMode == 0)
            {
                  while (this.current == this.old)
                  {
                        this.current = Math.floor(Math.random()*this.banners.length);
                  }
            }

            if (this.nowRotationMode == 1)
            {
                  this.current = this.current + 1;

                  if (this.current >= this.banners.length)
                  {
                        this.current = 0;
                  }
            }
      }

      this.old = this.current;


      document.images[this.imageName].src = this.banners[this.current];

      for (nowNumber = 0; nowNumber < document.links.length; nowNumber++)
      {
            if(document.links[nowNumber].name == this.anchorName)
            {
                  document.links[nowNumber].href = this.bannerLinks[this.current];
            }
      }


      setTimeout('this.Rotate()',this.rotateFrequency);
}



function RotatingBanner(inputImageName, inputAnchorName, inputBannerArray, inputBannerLinkArray, inputRotationMode, inputTimeout)
{
      this.old = 0;
      this.current = 0;
      nowRotationMode = inputRotationMode; // 0 = random, 1 = sequential
      this.nowIsFirstPass = 1;
      this.banners = inputBannerArray;
      this.bannerLinks = inputBannerLinkArray;
      this.imageName = inputImageName;
      this.anchorName = inputAnchorName;
      this.rotateFrequency = inputTimeout;
      this.Rotate = RotateBanner;

}
********************************************************
The object is instantiated by this code:
********************************************************
<a name="endorsementlink" href="test.html" target="_blank"><img src="" name="endorsement" border=0></a>
      <script language="javascript">
      var endorsements = new Array(
            '/commons/endorsements_ACCAPremierPlus.gif',
            '/commons/logo_Singapore_Quality.gif'
      );

      var endorsementLinks = new Array(
            'http://www.accaglobal.com/colleges/registrationscheme/benefits',
            'http://www.spring.gov.sg/'
      );


var nowEndorsements = new RotatingBanner('endorsement', 'endorsementlink', endorsements, endorsementLinks, 1, 3000);
nowEndorsements.Rotate();
</script>
********************************************************

The problem I have is with the timeout statement in the object's method:
      setTimeout('this.Rotate()',this.rotateFrequency);

If I do :
      setTimeout('this.RotateBanner()',this.rotateFrequency);
                The method will be called, but not with the same instance of the object (thus, all variables are undefined).

If I do:
      setTimeout('this.Rotate()',this.rotateFrequency);
                The browser complains that the function is undefined.

I need the instanced object to continue to call its own internal method.

How then, should this be done?

Yours Sincerely,
Jonah.

0
Comment
Question by:jugheadyong
4 Comments
 
LVL 51

Expert Comment

by:ahoffmann
ID: 18053435
your "this" dos no longer exist when the setTimout calls the function 'cause the namespace of this "this" (the surrounding function) allready exited and destroyed "this".
You should use a global variable.

Anyway that's strange 'cause the garbage collector should not destroy things if the ref counter is > 0 (like for "this" in this case).
0
 
LVL 6

Accepted Solution

by:
Basilisci earned 500 total points
ID: 18053838
Hi.

Instead of this:

     setTimeout('this.Rotate()',this.rotateFrequency);

try:

    var thisref = this;
    setTimeout(function() { thisref.Rotate(); }, this.rotateFrequency);

Assigning the object returned by the magical "this" statement to some normal variable ("thisref"), and enclosing it in a new function inside setTimeout, the correct object reference should be maintained when the timeout code is executed. I believe this behaviour is called "closure" in javascript.
0
 
LVL 7

Expert Comment

by:vbandaru
ID: 18059845
I believe Basilisci is right,. Here is an excellent article on closures..

http://developer.mozilla.org/en/docs/A_re-introduction_to_JavaScript#Closures
0
 

Author Comment

by:jugheadyong
ID: 18066649
Outstanding, Basilisci !  

And thanks for the link to the closures, vbandaru.  I have learnt something new about Javascript today.
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
javascript 5 43
Basic JavaScript Question 3 38
Split in Javascript 5 30
document.getElementById not worj with 2 IDs with the same name 10 17
Avoid defining the variables in the global scope; trying to define them in a local function scope. Because:   • Look-up is performed every time a variable is accessed.   • Variables are resolved backwards from most specific to least specific scope…
This article discusses the difference between strict equality operator and equality operator in JavaScript. The Need: Because JavaScript performs an implicit type conversion when performing comparisons, we have to take this into account when wri…
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…

911 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

26 Experts available now in Live!

Get 1:1 Help Now