这是一个来自javascript模式的currying片段:
function add(x, y) { var oldx = x, oldy = y; if (typeof oldy === "undefined") { // partial return function (newy) { return oldx + newy; } } // full application return x + y; }参考: https : //github.com/shichuan/javascript-patterns/blob/master/function-patterns/currying.html
当地的vars oldx和oldy有什么意义?
Here is a currying snippet from javascript patterns:
function add(x, y) { var oldx = x, oldy = y; if (typeof oldy === "undefined") { // partial return function (newy) { return oldx + newy; } } // full application return x + y; }ref: https://github.com/shichuan/javascript-patterns/blob/master/function-patterns/currying.html
What is the point of local vars oldx and oldy?
最满意答案
这里完全没有变量oldx和oldy ; 代码在没有它们的情况下表现相同:
function add(x, y) { if (typeof y === "undefined") { // partial return function (y) { return x + y; } } // full application return x + y; }此处返回的函数可以访问外部作用域变量,无论这些变量是使用var声明还是声明为外部函数的形式参数。
一般来说,如果x是基元,如果您需要该值的副本以独立于原始值进行更改,则有时将其分配给新变量是有意义的:
function foo(x) { var newX = x; newX += 7; // now newX and x are different // ... }但是 ,此代码中不存在该需求,因此完全没有必要。
The variables oldx and oldy are completely unnecessary here; the code behaves identically without them:
function add(x, y) { if (typeof y === "undefined") { // partial return function (y) { return x + y; } } // full application return x + y; }The function being returned here has access to outer-scope variables regardless of whether those variables are declared with var or declared as formal arguments to an outer function.
Generally speaking, if x is a primitive, it might sometimes make sense to assign it to a new variable if you needed a copy of that value to alter independently of the original:
function foo(x) { var newX = x; newX += 7; // now newX and x are different // ... }However, that need does not exist in this code, so it's totally unnecessary.
更多推荐
发布评论