非功能Javascript代码块中的返回值 [英] Return value in non-function Javascript code block

查看:116
本文介绍了非功能Javascript代码块中的返回值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试弄清Mike Bostock D3画廊的Box Plot示例中发生的情况.以下是可观察笔记本中的代码: https://observablehq.com/@d3/box-plot

I'm trying to work out what's going on in Mike Bostock's Box Plot example from the D3 gallery. Here's the code inside an Observable notebook: https://observablehq.com/@d3/box-plot

其中有一个似乎不是函数定义但具有返回值的代码块:

In it there's a code block that does not appear to be a function definition but that has a return value:

chart = {
    const svg = d3.select(DOM.svg(width, height));

    const g = svg.append("g")
        .selectAll("g")
        .data(bins)
        .join("g");

    // [...]

    return svg.node();
}

return不在函数定义中时会做什么或意味着什么?

What does return do or mean when it is not in a function definition?

推荐答案

是的,正如评论者所建议的那样,这是Observable特有的语法.您看到的是使用块的单元格,例如《代码简介》中提到的 .

Yep, as the commenters have suggested, this is a syntax that's particular to Observable. What you're seeing a cell that uses a block, as mentioned in the Introduction to Code.

相对于其他JavaScript,您如何看待它,就像是

How you can think of this relative to other JavaScript is that it's kind of like an IIFE, but with the added consideration that, if it references other cells, it automatically resolves them. So in vanilla JavaScript, this would be like:

chart = (() => {
    const svg = d3.select(DOM.svg(width, height));

    const g = svg.append("g")
        .selectAll("g")
        .data(bins)
        .join("g");

    // [...]

    return svg.node();
})()

实际上,这就是他们编译的大致内容.之所以采用这种特殊的语法,是因为它很清楚,它是在引用更改时运行的代码-请参见可观察的运行方式" 以获取更多信息.与IIFE不同,Observable中的单元格可能会运行多次,如果它引用的某些内容(例如生成器或Promise)发生了变化.

In fact, that's roughly what they compile to. The particular syntax is that way because it's meant to be clear that it's code that runs when references change - see how Observable runs for details on that. Unlike an IIFE, a cell in Observable might run multiple times, if something that it references, like a generator or Promise, changes.

这篇关于非功能Javascript代码块中的返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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