0

Given an ES6 class with generator function how do you run that generator function from ES5 code:

class GeneratorClass {

    constructor() {
        this.ary = [1, 2, 3];
    }

    *[Symbol.iterator]() {
        for (let el of this.ary) {
            yield el;
        }
    }

}

// This runs fine transcompiled (traceur)
var iterableObj = new GeneratorClass();
for (let el of iterableObj) {
    console.log(el);
}

From an ES5 testing framework:

TestCase('GeneratorClassTest', {
    setUp: function () {
        console.log('in setup');
        var iterableObj = new GeneratorClass();
        for (var el in this.iterableObj) {
            console.log(el);
        }
    },

    testConstructor: function() {

    }  
});

This does not throw any errors, will run the setup function, however does not iterate through the array.

4

1 回答 1

1

如果你只需要运行时只支持 ES5 的 ES6 模块,你不能这样做。

但是如果你使用babeltraceur将你的 ES6 模块编译成 ES5 ,然后需要你编译的模块——你可以在 ES5 运行时测试你的生成器。只是不使用for of循环,iteratorObj使用Symbol.iterator方法创建,使用when循环和next迭代器的方法。

对于您的示例:

TestCase('GeneratorClassTest', {
    setUp: function () {
        console.log('in setup');
        var generator = new GeneratorClass();
        var next, iterableObj = generator[Symbol.iterator]();

        while ((next = iterableObj.next()) && !next.done) {
            console.log(next.value);
        }
    },

    testConstructor: function() {

    }
});
于 2015-03-11T06:06:31.510 回答