0

I have the following code:

document.getElementById("whatever").addEventListener("click", function(e){
    
    var target = e.target;
    var search = "TR";
    do{
      if(target.nodeName.toUpperCase() === search) {
           window.setTimeout(function(){
               console.log(target);
           });
     
    }while(target = target.parentNode);
});

I was under the impression that since the variable target is in the outer scope of window.setTimeout, and inside the onclick event listener closure, it would be available to the scope of the setTimeout, but clearly that is not the case. Why is this? what is going on exactly here?

I know I can pass the context into set timeout anonymous function by doing this,

window.setTimeout(function(){
               console.log(this);
           }.bind(target); 

but I am still at a loss as to why target would not be available to the set timeout anonymous function as part of the event listener closure.

Apologies for misunderstanding of how closures work.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Pasha Skender
  • 397
  • 4
  • 21
  • The variable *is* in the scope. But by the time you access it, you had already iterated it until it's `null`. – Bergi Sep 05 '17 at 21:57

1 Answers1

1

Your variable is available inside the callback.

However, by the time the callback runs, the variable is null (since the while loop has finished).

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
  • I was under the impression that in a closure the variable was copied into a special place in memory with the state preserved at the moment of the closure creation. Does the setTimeout callback not create it's own closure separate from the event listener callback? Sorry if I am misunderstanding the concept. – Pasha Skender Sep 05 '17 at 21:54
  • 2
    @LorenShqipognja: No; a closure closes over _the original_ variable, and always reflects its current value. There are no copies. – SLaks Sep 05 '17 at 21:55
  • The `target` variable itself is closed over. The value of it at the time the function is created is not. – Quentin Sep 05 '17 at 21:56