1

当我们打电话

var xAxis = d3.svg.axis()

我们是在实例化一个新的轴对象吗?我知道该axis组件是作为闭包实现的,但如果它也是一个对象,我会感到困惑。

我的问题也适用于 Mike 的文章 Towards Reusable Charts,特别是本节的结尾。使用他的模式,如果我们做类似的事情

var myChart = chart().width(720).height(80);

myChart一个对象?如果不是,那是什么?做这个和做有什么区别var myChart = new chart();

4

1 回答 1

3

是的,我们每次都实例化一个新的轴对象。这个实例是 a function,它在 JavaScript 中是一等 Object;意思是,您可以像这样为其分配属性:

function myFunc() {}
myFunc.foo = "bar";

myFunc();// This is possible (naturally)
console.log(myFunc.foo);// ...and this is valid too

如果将上面的代码包装在一个函数中:

function giveMeMyFunc() {
    function myFunc() {}
    return myFunc;
}

然后每次你打电话

myFuncInstance = giveMeMyFunc();

你会得到一个新的实例myFunc(它也是一个对象),因为myFunc每次调用都会声明一次。

所以我们已经确定一个函数也是一个对象。而且,当一个函数返回另一个函数时,就好像它返回了一个对象的新实例,但同时也是一个函数,你仍然可以调用myFuncInstance().

为了强调这一点,也许为了回答您的其他问题,我们可以看看d3.svg.axis()实际是如何实现的(大致摘自 d3 源代码):

d3.svg.axis = function() {
  /* Some variables here, which essentially are instance properties (protected through closure) */
  var scale = 123;
  ...

  /* This is a function, but since JavaScript functions are first-class objects, it's essentially an instance. */
  /* Each time (the outer) `d3.svg.axis()` is called, (the inner) `axis` function is a unique – not a shared – object. */
  function axis() {
    /* This is where the work of drawing the axis takes place, but won't get
      called until the axis is used (see below). */
  }

  /* Since the inner function `axis` is also an object, the following is an instance method */
  axis.scale = function(x) {
    scale = x;// here we're setting `scale`, which is basically an instance property

    // returning `axis` – a.k.a. our instance – is what enables method chaining: myAxis.scale(5).orient("left")
    return axis;
  }

  /* More methods here, like `axis.scale` above */

  /* Last line is very important: */
  /* This is where the newly created instance is return. Remember from */
  /* above, `axis` is a function, but it's an Object too, and it has the */
  /* methods we've just applied to it. */
  return axis;
}


/* Given all that, the line below returns an instance of `axis` (the inner function),
  which has more methods applied to it. */
myAxis = d3.svg.axis();

最后,由于实例myAxis也是一个函数,你可以调用它。这就是 d3 在将轴应用于选择时所做的事情:

d3.select('.x_axis').call(myAxis);

D3 将调用myAxis其主体的函数,上面定义的主体function axis() {}将完成在匹配选择器的元素中实际绘制一些 SVG 内容的所有工作'.x_axis'

于 2013-02-01T22:48:37.007 回答