gpt4 book ai didi

javascript - 从函数定义中引用 GeneratorFunction 实例

转载 作者:行者123 更新时间:2023-11-30 15:24:19 24 4
gpt4 key购买 nike

我想在实例化的 GeneratorFunction 上设置属性。为了方便起见,我希望能够设置 length 属性,以便消费者了解将生成多少个值。例如:

function* produceValues(someInput) {
this.length = determineLength(someInput)
yield // something
}

const gen = produceValues(input)
console.log(gen.length)

毫不奇怪,使用this 不是指实例,而是指全局。 JavaScript 是否提供某种方式来访问实例化对象?

最佳答案

不,不幸的是不是,因为 this 适用于将生成器函数用作方法,而不是用作构造函数(它们是)。所以你所能做的就是

function* _produceValues(someInput) {
yield // something
}
function produceValues(someInput) {
var res = _produceValues(someInput);
res.input = someInput;
// or res.length = …
return res;
}
produceValues.prototype = Object.defineProperties(_produceValues.prototype, {
length: {
get() { return determineLength(this.input); }
}
});

const gen = produceValues(input);
console.log(gen instanceof produceValues);
console.log(gen.input);
console.log(gen.length);

我们还可以给它一些疯狂的语法糖:

function generatorClass(genFun) {
function constructor(...args) { return Object.setPrototypeOf(genFun(...args), new.target.prototype); }
constructor.prototype = genFun.prototype;
return constructor;
}
class produceValues extends generatorClass(function*(someInput) {
yield // something
}) {
constructor(someInput) {
super(someInput);
this.input = someInput;
}
get length() {
return determineLength(this.input);
}
}

但是你必须使用 const gen = new produceValues(input)。尽管 gen 是一个具有额外属性的特殊生成器实例,但它会变得很清楚。

关于javascript - 从函数定义中引用 GeneratorFunction 实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43219010/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com