My JavaScript Secrets

This pointer and setTimeout() Usage

Function.prototype.bind()  [ The text is a copy from the reference below ]

The bind() method creates a new function that, when called, has its this keyword set to the provided value, 
with a given sequence of arguments preceding any provided when the new function is called.

With setTimeout

By default within window.setTimeout(), the this keyword will be set to the window (or global) object. 
When working with class methods that require this to refer to class instances, you may explicitly bind 
this to the callback function, in order to maintain the instance.

Track.prototype.flashTrack = function() 
   logMessage3("Track.prototype.flashTrack():: - flashIDX: " + this.flashIDX );
   if ( (this.flashIDX) % 2 == 1 ) 
      // see 
   setTimeout(this.flashTrack.bind(this), 1000 );


  Java Script Closures

 A closure is a function having access to the parent scope, even after the parent function has 
 function say667() {
    // Local variable that ends up within closure
    var num = 666;
    var say = function() { console.log(num); }
    return say;
    var sayNumber = say667();
    sayNumber(); // alerts 667

  Two one sentence summaries:
    - a closure is the local variables for a function — kept alive after the function has 
    - a closure is a stack-frame which is not deallocated when the function returns (as if 
      a 'stack-frame' were malloc'ed instead of being on the stack!).

 Most JavaScript programmers will understand how a reference to a function is returned to a
 variable (sayNumber) in the above code.  If you don't, then you need to before you can learn 
 closures. A C programmer would think of the function as returning a pointer to a function, and 
 that the variables say and say2 were each a pointer to a function.
 There is a critical difference between a C pointer to a function and a JavaScript reference to 
 a function. In JavaScript, you can think of a function reference variable as having both a 
 pointer to a function as well as a hidden pointer to a closure.
 The above code has a closure because the anonymous function function() { console.log(num); } 
 is declared inside another function, say667() in this example. In JavaScript, if you use 
 the function keyword inside another function, you are creating a closure.

 In C and most other common languages, after a function returns, all the local variables are 
 no longer accessible because the stack-frame is destroyed.

 In JavaScript, if you declare a function within another function, then the local variables 
 can remain accessible after returning from the function you called. This is demonstrated 
 above, because we call the function say() after we have returned from say667(). 
 Notice that the code that we call references the variable num, which was a local variable 
 of the function say667().


Leave a Reply

Your email address will not be published. Required fields are marked *