d3.js / 不使用调用方法,可以查看x轴?

d3.js / without using the call method, you can view the x-axis?

当前代码 / 使用的调用方法

var svg = d3.select("#hoge").append("svg")
    .attr("width", 600).attr("height", 400)
var xScale = d3.scale.linear()
    .domain([0, 100])
    .range([0, 400]);
svg.append("g")
    .attr("class", "axis")
    .call(d3.svg.axis()
        .scale(xScale)
    );

我想知道 / 未使用的调用方法

var svg = d3.select("#hoge").append("svg")
    .attr("width", 600).attr("height", 400)
var xScale = d3.scale.linear()
    .domain([0, 100])
    .range([0, 400]);
svg.append("g")
    .attr("class", "axis");

d3.svg.axis(svg).scale(xScale);

如果不使用call方式 x轴无法显示?

d3.svg.axis() 创建并 returns 一个附加 SVG 元素以显示轴的函数。它实际上并没有附加任何东西。如果您不调用返回的函数,则不会添加这些元素。这是 d3.js 中的常见模式,因此理解它很重要。

假设您为轴函数和轴组元素创建了这两个变量:

var axisFunction = d3.svg.axis().scale(xScale);
var axisGroup = svg.append("g")
    .attr("class", "axis");

以下两种调用轴函数的方式是等价的:

axisFunction(axisGroup);
axisGroup.call(axisFunction);

call 语法的存在只是为了像您当前的代码示例中那样启用方法链接。

The call operator is identical to invoking a function by hand; but it makes it easier to use method chaining.

https://github.com/mbostock/d3/wiki/Selections#call

Mike Bostock 的文章 Towards Reusable Charts 很好地解释了这种模式。本文中描述的用于创建可重用图表的模式用于 d3.js 中的各种项目,例如 d3.svg.axis