簡體   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