1

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));

3 Answers 3

1

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));
Sign up to request clarification or add additional context in comments.

2 Comments

@ShanKhan, I will prefer not to answer ;) You are suppose to understand both Closures as well as Function#bind to make any move..Both have totally different purpose.. ;)
can you give me a good link that provides a fundamental different purpose so i can understand, i have seen examples but those can be performed by both.
0

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.

Comments

0

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));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.