我试图搜索这个 JavaScript 函数的解释。我想了解这个函数是如何获取值的?有人可以推荐一个地方,让我可以阅读更多关于以这种方式传递/使用值(value)的信息。
pie.value = function(_) {
if (!arguments.length) return value;
value = _;
return pie;
};
此代码来自 D3 JS。
最佳答案
它是一个依赖闭包的 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
现在在案例 B 中,您可以看到 getterSetter 返回了自己。这样它就变得(有点)可链接,这意味着您可以:
getterSetter(1)(2)(3)(); // assign 1 then 2 then 3 and displays 3;
你的情况有点不同,因为在情况 B 中返回的是 pie
对象,而不是函数 pie.value,这意味着你可以这样做:
pie.value(1).value(2).value(3).value();
关于javascript - 对 JavaScript 的理解,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28357813/