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.