ES6发生器功能中的星号(*)的目的是什么? [英] What purpose of asterisk (*) in ES6 generator functions

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

问题描述

有人可以向我解释:为什么ES6中的发电机功能标有星号符号?



例如,而不是:

  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 运算符,并从此函数中生成生成器。



为什么检测收益存在是不够的?

解决方案


  1. 可读性。一个发生器与一个函数完全不同,差异应该是立即可见的(也就是说,没有检查整个实现来搜索收益)。


  2. 概论。自然可能写出不产生的发电机,只能直接返回。此外,注释掉身体的一部分(例如,用于调试)不应该默认地改变是否有发生器。


  3. 兼容性。只有严格模式保留'yield'作为关键字,但ES6的目标是使所有新功能也可以以马虎模式(不幸的决定IMHO,但是仍然)。而且,即使在严格的模式下,围绕'yield'有许多解析微妙;例如,考虑默认参数:

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

    如果没有 * ,解析器只能决定在看到功能的正文之后解析产量。也就是说,您将需要无限的预先或后跟踪或其他黑客技术来处理此问题。


我应该注意到(1)和(2)已经是足够的理由了。



(全面披露:我是EcmaScript委员会的成员)。 >

Can someone explain to me: why generator function in ES6 is marked by asterisk symbol?

For example, instead of:

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

we could write:

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

or even:

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

var someObject = {

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

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

Why detection of yield existence is not enough?

解决方案

The three reasons were:

  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).

  2. 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.

  3. 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.

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

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

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

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