【问题标题】:Javascript - Get prototype to return generatorJavascript - 获取原型以返回生成器
【发布时间】:2016-06-27 18:50:11
【问题描述】:

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

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 的原型中。

类似这样的:

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

此时我得到错误:

意外的标记“*”。期望在函数之前有一个开头的“(” 参数列表。

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

【问题讨论】:

    标签: javascript constructor iterator prototype generator


    【解决方案1】:

    通常,如果您希望类的实例是可迭代的,则无需创建额外的包装器。只需为类定义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);
    }
    

    【讨论】:

    • 但是如果我想拥有多个不同的迭代器怎么办?像一个迭代字符串属性和一个迭代整数属性?
    • @LastSecondsToLive:在这种情况下,您的代码很好。您使用的是哪个转译器?
    • 抱歉,我不知道我使用的是什么跨极。几天前,我刚从强大的C-背景中凝视。我只是在编写 .js 文件来美化我的网页。奇怪的是,您的 tinyurl 中的代码有效,我仍然收到相同的错误消息。
    • 啊,我想我明白了。正如this 主页所述。 Safari(我正在使用)目前不支持生成器。现在我必须想出一个替代方案。
    猜你喜欢
    • 2016-06-02
    • 2019-07-03
    • 1970-01-01
    • 2020-09-22
    • 2019-09-02
    • 2023-03-10
    • 2019-01-31
    • 1970-01-01
    相关资源
    最近更新 更多