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));
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));
It works normally. The scope of the ul
is valid inside the setTimeout
function.
ul.find("li").each(function() {
$(this).attr("tabindex", options.items[a].tabindex)
.on("focusout", function() {
setTimeout(function() {
ul.css('color', 'orange');
}, 1);
});
});
A simple code like this will explain you:
(function s() {
var a = "hi";
setTimeout(function () {
console.log(a);
}, 1000);
})();
Here, the ul
is the same as the a
variable.
You can use access the UL by finding the parent of current element. For getting the immediate parent with specified type, you can use .closest()
method
$(ele).on("focusout", function() {
var el = $(this);
setTimeout(function() {
el.closest("ul");
debugger;
}, 1);
}.bind(ul, ele));