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

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

问题描述

我正在尝试弄清楚 D3 画廊中 Mike Bostock 的 Box Plot 示例中发生了什么.这是 Observable 笔记本中的代码: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,您如何看待它有点像 IIFE,但要额外考虑的是,如果它引用其他单元格,它会自动解析它们.所以在原生 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();
})()

事实上,这大致就是他们编译的结果.特定的语法是这样的,因为它意味着清楚它是在引用更改时运行的代码 - 请参阅 Observable 如何运行 了解详情.与 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天全站免登陆