为什么在Javascript中使用这种语法(从函数返回函数)
这段代码来自AngularJS源代码,其中有很多“函数返回函数”样式的代码为什么在Javascript中使用这种语法(从函数返回函数),javascript,Javascript,这段代码来自AngularJS源代码,其中有很多“函数返回函数”样式的代码 function locationGetterSetter(property, preprocess) { return function(value) { if (isUndefined(value)) return this[property]; this[property] = preprocess(value); this.$$compose(); return
function locationGetterSetter(property, preprocess) {
return function(value) {
if (isUndefined(value))
return this[property];
this[property] = preprocess(value);
this.$$compose();
return this;
};
}
这比一个带有额外参数的“常规”函数有什么好处-
function locationGetterSetter(property, preprocess, value) {
if (isUndefined(value))
return this[property];
this[property] = preprocess(value);
this.$$compose();
return this;
}
在本例中,它似乎是一个用于为值生成setter/getter函数的函数 如果看不到更多的上下文,我们只能猜测为什么会这样做。然而,从外观上看,我可以想象它被用来更容易地生成具有特定行为的动态对象(例如,通过某些验证获取/设置值) 与您的备选方案相比,考虑到返回的函数使用
this
关键字,它甚至可能不会这样工作。它很可能被分配到一个对象中,因此此
将引用该对象
正如注释中指出的,它本质上是curry,但也有可能用于生成函数的数据在使用生成函数的后期阶段无法作为参数传递,因为angular使用数据绑定进行一些编译/链接,其中信息可能仅在编译/链接阶段可用
关闭这两个参数也可能会带来一些非常(非常)微小的性能好处。基本上是咖喱。咖喱有什么好处?你不必每次都传递不变的参数,甚至不必知道它们是什么或它们是否存在。这是科林克: