gpt4 book ai didi

Javascript - 获取原型(prototype)以返回生成器

转载 作者:行者123 更新时间:2023-11-30 00:12:18 25 4
gpt4 key购买 nike

在我当前的 JS 项目中,我有一个,它看起来像这样:

function MyClass() {
this.prop1 = true;
this.prop2 = "Hello World";
this.prop3 = "This is another String.";
this.prop4 = "Just another string here.";
}

我希望能够使用 Generator 遍历字符串.我可以通过这样做来实现它:

function* createStringIteratorFromMyClass(myclass) {
yield myclass.prop2;
yield myclass.prop3;
yield myclass.prop4;
}

现在我可以像这样遍历字符串:

for(const str createStringIteratorFromMyClass(...)) {
// access str here
}

效果很好,但我想将 createStringIteratorFromMyClass 添加到 MyClass 的原型(prototype)中。

像这样:

MyClass.prototype.createStringIterator = function* () {
yield this.prop2;
yield this.prop3;
yield this.prop4;
}

此时我得到错误:

Unexpected token '*'. Expected an opening '(' before a function's parameter list.

如何添加一个函数,该函数将生成器返回到我的类的原型(prototype)?

最佳答案

通常,如果您希望类的实例可迭代,则无需创建额外的包装器。只需为类定义 Symbol.iterator 即可:

function MyClass() {
this.prop1 = true;
this.prop2 = "Hello World";
this.prop3 = "This is another String.";
this.prop4 = "Just another string here.";
}

MyClass.prototype[Symbol.iterator] = function* () {
yield this.prop2;
yield this.prop3;
yield this.prop4;
}

let x = new MyClass()

for(const str of x) {
console.log(str);
}

关于Javascript - 获取原型(prototype)以返回生成器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35958628/

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