2015-02-06 70 views
3

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

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

此代码来自D3 JS。

+1

这是不可能的说,因为'价值'没有在你发布的代码中声明。该函数内部的符号'value' * *不与* pie对象的属性名称相同。 – Pointy 2015-02-06 02:57:22

+0

你的意思是[http://underscorejs.org/](http://underscorejs.org/)? – amitthk 2015-02-06 02:59:09

+0

“这样”是什么意思?它只是以正常的方式传递一个参数。参数的名称是'_'。 – Barmar 2015-02-06 03:11:26

回答

6

这是一个依靠关闭的吸气/吸气器。

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; 

你的情况是因为pie对象在实例B返回有点差别,而不是功能pie.value,这意味着你可以做到这一点:

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

好吧现在我明白了,我没有看到顶部的变量。 – 2015-02-06 06:17:01