Shan Khan Shan Khan - 5 months ago 13
jQuery Question

How to access variable from Closure Scope in Javasript

How to access the closure scope variables in inner function in JavaScript.

I want to access UL variable in

setTimeout
function.

ul.find("li").each(function (a, ele) {

$(ele).attr("tabindex", options.items[a].tabindex);

$(ele).on("focusout", function () {

setTimeout(function () {
**//ACCESS UL HERE**
debugger;
}, 1);

}.bind(ul,ele));
}.bind(ul));

Answer

Using closure in setTimeout

Closures 'remember' the environment in which they were created.

ul.find("li").each(function(a, ele) {
  $(ele).attr("tabindex", options.items[a].tabindex);
  $(ele).on("focusout", function() {
      setTimeout(function(ul) {
        return function() {
          console.log(ul);
        }
      })(ul), 1);
  }.bind(ul, ele));
}.bind(ul));