Return value in non-function Javascript code block

浪子不回头ぞ 提交于 2019-12-04 05:22:40

问题


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();
}

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


回答1:


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.

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();
})()

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.



来源:https://stackoverflow.com/questions/55865124/return-value-in-non-function-javascript-code-block

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!