How to access variable from Closure Scope in JavaScript

流过昼夜 提交于 2019-12-13 12:44:09

问题


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

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



回答2:


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.




回答3:


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


来源:https://stackoverflow.com/questions/38052714/how-to-access-variable-from-closure-scope-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!