在闭包中为局部变量赋值(Assigning arguments to local variables in closure)

编程入门 行业动态 更新时间:2024-10-17 21:26:46
在闭包中为局部变量赋值(Assigning arguments to local variables in closure)

这是一个来自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.

更多推荐

本文发布于:2023-04-27 13:40:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1326402.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:赋值   变量   中为   局部   Assigning

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!