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

时间:2016-03-12 14:08:05

标签: javascript constructor iterator prototype generator

在我目前的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的原型中。

这样的事情:

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

此时我收到错误:

  

意外的标记'*'。期待一个开头'''在一个函数之前   参数列表。

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

1 个答案:

答案 0 :(得分: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);
}