问题描述
我正在寻找一种方法来为使用 function*()
构造的生成器公开其他属性。我尝试了两种幼稚的方法,但都没有达到我想要的效果。
方法 1 说明了我想要做什么,天真地尝试使用 this
将属性附加到生成器:
function* counter(startValue) {
// trying to expose a property through "this",// which does not work as intended
// (I actually expected this,but it illustrates what I am trying to do)
this.startValue = startValue;
// simple counter
let currentValue = startValue;
while (true) yield currentValue++;
}
// user code
let myCounter = counter(10);
console.log(myCounter.next().value);
// -> 10
console.log(myCounter.next().value);
// -> 11
// I want myCounter.startValue to expose the start value (10)
// unfortunately this does not work
console.log(myCounter.startValue);
// -> undefined
方法二,尝试使用闭包来存储起始值:
// use a closure to store configuration & state
function counter(startValue) {
let currentValue = startValue;
let gen = function*() {
while(true) yield currentValue++;
}
// Again,I want the generator to expose the "startValue" parameter
// This also does not work:
gen.startValue = startValue;
return gen;
}
// user code
let myCounter = counter(10)();
myCounter.next().value;
// -> 10
myCounter.next().value;
// -> 11
// Again,no luck accessing the start value
myCounter.startValue;
// -> undefined
我猜因为实际的生成器对象是由 JS 运行时隐式构造的,所以没有办法在不创建某种包装器对象的情况下为其附加其他属性?
(由于整个项目结构的原因,构造生成器然后附加属性(myCounter.startValue = 10
在用户代码中的某处)对我来说不是一个选择,它必须在构造函数中完成)
解决方法
您的关闭尝试是正确的方法,您只是错过了在函数内部创建生成器(您想要附加属性的),而不是将其附加到生成器函数:
function* count(currentValue) {
while(true) yield currentValue++;
}
function counter(startValue) {
const gen = count(startValue);
gen.startValue = startValue;
return gen;
}
let myCounter = counter(10);
myCounter.next().value; // -> 10
myCounter.next().value; // -> 11
myCounter.startValue; // -> 10