ES6生成器函数中的星号(*)的作用是什么 [英] What's the purpose of an asterisk (*) in ES6 generator functions

查看:725
本文介绍了ES6生成器函数中的星号(*)的作用是什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以向我解释:为什么ES6中的生成器功能用星号标记?

Can someone explain to me: why are generator functions in ES6 marked by asterisk symbol?

例如,代替:

function *someGenerator() {
    yield 1;
    yield 2;
    yield 3;
}

我们可以这样写:

function someGenerator() {
    yield 1;
    yield 2;
    yield 3;
}

甚至:

var someGenerator = () => {
    yield 1;
    yield 2;
    yield 3;
}

var someObject = {

    someGenerator() {
        yield 1;
        yield 2;
        yield 3;
    }
}            

JS编译器可以在解析时检测到someGenerator包含yield运算符,并从此函数生成一个生成器.

The JS compiler can detect that someGenerator contains yield operator at the parse time and make a generator from this function.

为什么对yield存在的检测不够?

Why is detection of yield existence not enough?

推荐答案

三个原因是:

  1. 可读性.生成器与函数完全不同,并且该区别应立即可见(也就是说,无需检查整个实现以获取产量).

  1. Readability. A generator is quite different from a function, and the difference should be immediately visible (that is, without examining the whole implementation in search for a yield).

通用性.自然应该可以编写不屈服的生成器,而只能直接返回.此外,注释掉主体的一部分(例如用于调试)不应默默地更改某些东西是否是生成器.

Generality. It should be naturally possible to write generators that do not yield, and only return directly. Moreover, commenting out part of the body (e.g. for debugging) should not silently change whether something is a generator.

兼容性.只有严格模式保留了"yield"作为关键字,但是ES6的目标是所有所有新功能也都可以在草率模式下使用(不幸的是,恕我直言,尽管如此).而且,即使在严格模式下,"yield"周围也有许多解析的细节.例如,考虑默认参数:

Compatibility. Only strict mode reserved 'yield' as a keyword, but it was made a goal for ES6 that all new features are also available in sloppy mode (an unfortunate decision IMHO, but nevertheless). Moreover, even in strict mode there are many parsing subtleties around 'yield'; for example, consider default arguments:

function* g(a = yield(2)) { 'use strict' }

没有*,解析器只能在看到函数的主体之后决定如何解析收益.也就是说,您将需要无限的前瞻,回溯或其他黑客手段来解决此问题.

Without the *, the parser could only decide how to parse the yield after it has seen the body of the function. That is, you would need infinite look-ahead, or back-tracking, or other hacky techniques to deal with this.

我应该注意,(1)和(2)已经足够了.

I should note that (1) and (2) are already reason enough.

(完全公开:我是EcmaScript委员会的成员.)

(Full disclosure: I am a member of the EcmaScript committee.)

这篇关于ES6生成器函数中的星号(*)的作用是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆