繁体   English   中英

如何在递归函数中使用闭包而不丢失JavaScript的作用域?

[英]How to use closure in a recursive function without losing scope in JavaScript?

  • tem.jqw.Callback对象包含一个可执行函数,即CSS选择器。 和循环延迟。
  • tem.jqw.wait等待jQuery加载,然后遍历tem.jqw.Callback对象的数组,并在找到传入CSS选择器的元素后执行其功能。

我遇到的问题是tem.jqw.Callback对象中的run函数。 首次调用运行功能时,如果元素存在,则一切正常,可执行功能运行正常。 但是,如果该元素尚不存在,并且需要循环,则在setTimeout(this.run,100)执行一次之后,该函数将失去作用域。 例如,当运行功能第二次执行时,this.selector或this.fn变为未定义。 如何不使用全局变量来解决此问题? 提前致谢。

 if (typeof tem !== "object") { tem = {}; } tem.jqw = {}; tem.jqw.retries = 0; tem.jqw.maxRetries = 100; tem.jqw.delay = 100; tem.jqw.callbacks = []; tem.jqw.Callback = function (fn, selector, delay) { this.fn = fn; this.selector = (typeof selector === "string" && selector.length > 0) ? selector : document; this.delay = (typeof delay === "number" && delay > 0 && delay < 1000) ? delay : 100; this.retries = 0; this.maxRetries = 100; this.start = function () { this.run(); }; this.run = function () { if (jQuery(this.selector).length > 0) { console.log("[OPDEBUG] tem.jqw.Callback.run says: " + this.selector.toString() + " is ready. Executing callback function..."); this.fn(); } else { this.retries++; console.log("[OPDEBUG] tem.jqw.Callback.run says: typeof this.selector " + typeof this.selector); console.log("[OPDEBUG] tem.jqw.Callback.run says: Waiting for " + this.selector.toString() + "..."); if (this.retries < this.maxRetries) { setTimeout(this.run, 100); } } }; }; tem.jqw.wait = function () { if (typeof jQuery === "function") { console.log("[OPDEBUG] tem.jqw.wait says: jQuery is ready."); for (var i = 0; i < tem.jqw.callbacks.length; i++) { if (typeof tem.jqw.callbacks[i] === "object" && typeof tem.jqw.callbacks[i].start === "function") { console.log("[OPDEBUG] tem.jqw.wait says: Executing callback function " + (i + 1) + "..."); tem.jqw.callbacks[i].start(); } } } else { tem.jqw.retries++; console.log("[OPDEBUG] tem.jqw.wait says: " + "Waiting for jQuery " + tem.jqw.retries + "..."); if (tem.jqw.retries < tem.jqw.maxRetries) { setTimeout(tem.jqw.wait, tem.jqw.delay); } } }; tem.jqw.callbacks.push(new tem.jqw.Callback(function () { jQuery('.hero-inner:first a').css('background-image', 'url("https://www.thedogs.co.nz/Files/PhotoFinishImages/11298_89160.jpg")') }, ".hero-inner:first")); tem.jqw.callbacks.push(new tem.jqw.Callback(function () { jQuery('.RR-placeholder ul li:first').hide(); }, ".RR-placeholder ul li:first")); tem.jqw.wait(); 

您可以使用绑定设置此

this.run()更改为

this.run.bind(this)

它能够更好地分配另一个变量如)

var self = this;

然后绕过自我以获得更好的可读性

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM