如何在对象字面量或类中定义生成器属性?
如何在JavaScript对象或类中定义生成器属性?
JavaScript 在对象字面量和类中支持属性 getter 的语法:
var stuff = { get things() { return ['thimbles', 'care', 'forks', 'hope']; }, }; class Foo { get things() { return ['thimbles', 'care', 'forks', 'hope']; } }; // 使用示例 [ ...stuff.things ] var foo = new Foo; for (let thing of foo.things) { // … }
它还支持生成器方法的语法:
var stuff = { *things() { yield* ['thimbles', 'care', 'forks', 'hope']; }, }; class Foo { *things() { yield* ['thimbles', 'care', 'forks', 'hope']; } }; // 使用示例 [ ...stuff.things() ] var foo = new Foo; for (let thing of foo.things()) { // … }
那么如何将二者结合,在对象或类中定义生成器属性呢?以下是一些尝试直接结合 getter 语法与生成器方法语法但会产生语法错误的示例:
// 抛出 "SyntaxError: Unexpected token '*'" var stuff = { get* things() { yield* ['thimbles', 'care', 'forks', 'hope']; }, }; // 抛出 "SyntaxError: Unexpected token '*'" class Foo { get *things() { yield* ['thimbles', 'care', 'forks', 'hope']; } }; // 抛出 "SyntaxError: Unexpected identifier 'things'" stuff = { *get things() { yield* ['thimbles', 'care', 'forks', 'hope']; }, }; // 期望的使用方式 [ ...stuff.things ]; var foo = new Foo; for (let thing of foo.things) { // … }
注意:示例中使用了静态数组,但实际应用场景会是生成序列,例如DOM查询的结果;不使用生成器并非解决方案。同样,虽然可以用生成器方法替代属性,但计算属性的相关论点同样适用(例如方法会暴露底层实现)。
解决方案
要实现生成器属性,核心思路是让getter返回一个生成器对象。每次访问属性时,getter创建并返回新的生成器实例,保证每次遍历都是独立的序列。
对象字面量实现
var stuff = { get things() { // 定义生成器函数并立即调用返回生成器对象 return (function* () { yield* ['thimbles', 'care', 'forks', 'hope']; })(); }, }; // 使用方式 [...stuff.things]; // ['thimbles', 'care', 'forks', 'hope'] for (let thing of stuff.things) { console.log(thing); }
类实现
class Foo { get things() { function* generator() { yield* ['thimbles', 'care', 'forks', 'hope']; } return generator(); } }; // 使用方式 const foo = new Foo(); [...foo.things]; // ['thimbles', 'care', 'forks', 'hope'] for (let thing of foo.things) { console.log(thing); }
内容的提问来源于stack exchange,提问作者outis
相关产品推荐
相关产品推荐

