簡體   English   中英

從javascript生成器對象內部引用自身

[英]Reference to itself from inside a javascript generator object

我試圖用迭代器函數和yield替換對alert()的調用

參見下面一個非常基本的代碼段

 var globalFunction; function* test () { /* test is a generator function. It will return an iterator function after this iterator function yields, I want it to continue when the button2 is clicked. (Just as if the button2 is the button in an alert) Note than here the iterator function still doesn't exist, it will be returned at the end of the generator function */ var ele = document.getElementById("btn2"); ele.onclick = function () { globalFunction.next(); /* use some kind of 'this' here ? */ }; yield 1; console.log ("test2"); yield 2; } function btn1 () { console.log ("btn1"); var mytest = test(); globalFunction = mytest; var res = mytest.next(); console.log (res.value); } 
 <button id="btn1" onclick="btn1()">BTN1</button> <button id="btn2">BTN2</button> 

該代碼段有效,因為我將迭代器存儲在全局變量中,然后在需要時將其分配給onclick。

但是我不喜歡這種工作方式。

我希望能夠以某種方式訪問​​迭代器功能。 關於使用this的評論。

知道 在這里行不通!

但是,這里沒有任何方法可以獲取對迭代器函數的引用嗎?

另一個要澄清的例子:

 var globalFunction; var span = document.getElementById("res"); function* test() { /* test is a generator function. It will return an iterator function after this iterator function yields, I want it to continue when the button2 is clicked. (Just as if the button2 is the button in an alert) Note than here the iterator function still doesn't exist, it will be returned at the end of the generator function */ var ele = document.getElementById("btn2"); ele.onclick = function() { globalFunction.next(); /* use some kind of 'this' here ? */ }; var x; for (x = 1;; x++) { if (x % 7 == 0) { span.innerHTML = x + ' is divisible by 7. Hit btn2 to continue'; yield; } } } function btn1() { console.log("btn1"); var mytest = test(); globalFunction = mytest; var res = mytest.next(); } 
 <button id="btn1" onclick="btn1()">BTN1</button> <button id="btn2">BTN2</button> <span id="res">Hit BTN1</span> 

最后,我想出了一個解決方案,以在生成器對象內部引用自身(某種)

function runGenerator (gen) {

    function* wrapper () {
        var reflection = yield;

        yield* gen(reflection);
    }
    var genObj = wrapper();
    genObj.next();
    return genObj.next(genObj);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM