问题
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