了解JavaScript

时间:2015-02-06 02:55:33

标签: javascript function

我试图搜索这个JavaScript函数的解释。我想了解这个函数是如何获得价值的?有人可以建议一个我可以通过这种方式阅读更多关于传递/使用价值的地方。

pie.value = function(_) {
    if (!arguments.length) return value;
    value = _;
    return pie;
};

此代码来自D3 JS。

1 个答案:

答案 0 :(得分:6)

这是一个依赖于闭包的getter / setter。

var value = 5; // initial value

var getterSetter = function(newValue) {
  // value is closed from the outer scope
  if (!arguments.length) {
    // CASE A
    return value;
  }
  // // CASE B
  value = newValue;
  return getterSetter;
};

getterSetter()   // arguments.length is 0 (CASE A) so displays value (5)

getterSetter(10) // arguments.length is 1 (CASE B) so values is set to 10

getterSetter()   // now this displays 10 since value now is 10 (CASE A)

console.log(value); // Also displays 10, this is the same value variable

现在在CASE B中,您可以看到getterSetter返回自身。通过这种方式,它变成了可链接的,这意味着你可以这样做:

getterSetter(1)(2)(3)(); // assign 1 then 2 then 3 and displays 3;

你的情况有点不同,因为在CASE B中返回了pie对象,而不是函数pie.value,这意味着你可以这样做:

pie.value(1).value(2).value(3).value();