我试图用迭代器函数替换对alert()的调用,并且 yield
请参阅下面一个非常基本的代码段
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>
&#13;
这段代码正在运行,因为我将迭代器存储在全局变量中,然后在需要时将其与onclick对齐。
但我不喜欢这种工作方式。
我希望能够以某种方式访问迭代器函数。在有关使用此的评论时。
我知道 这个在这里工作了!
但是,有没有办法在这里获得对迭代器函数的引用?
另一个澄清的例子:
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();
}
&#13;
<button id="btn1" onclick="btn1()">BTN1</button>
<button id="btn2">BTN2</button>
<span id="res">Hit BTN1</span>
&#13;
答案 0 :(得分:0)
最后,我想出了一个解决方案,在生成器对象中引用自身(有点)
function runGenerator (gen) {
function* wrapper () {
var reflection = yield;
yield* gen(reflection);
}
var genObj = wrapper();
genObj.next();
return genObj.next(genObj);
}