简体   繁体   English

如何保存返回值?

[英]How are return values saved?

Does a method/function's call statement hold its return value similar to a how a variable name holds a value? 方法/函数的调用语句是否保留其返回值,类似于变量名如何保留值?

For example: 例如:

function Jump(height) {
    return height * 2;
}
Jump(3);       //Is the call statement 'Jump(3)' equal the return value of 6 similar to

var x = 3;  //how the variable 'x' is equal to the value of 3?

Edit: I gave the wrong impression by naming the variable and function the same name. 编辑:通过给变量和函数命名相同的名称,我给人留下了错误的印象。 I was purely using the variable as a comparison in understanding how return values are saved. 在理解返回值的保存方式时,我纯粹是使用变量作为比较。 I'll word/structure my question better next time. 下次我会更好地表达/构造我的问题。

functions and variables share the same namespace. 函数和变量共享相同的名称空间。 You defined the function Jump and then called it (but didn't actually assign the results of the function (what was returned)), so it returned 6 but then you didn't actually store it anywhere. 您定义了函数Jump ,然后对其进行了调用(但实际上并未分配该函数的结果(返回的结果)),因此它返回了6,但实际上并未将其存储在任何地方。 Then you overwrote your function by redefining it as a variable with the same name, and just assigned it the value of 3 然后,通过将函数重新定义为具有相同名称的变量来覆盖函数,并为其分配值3

A little about expressions 关于表达的一点

Following your edit, it seems you're asking about expressions . 编辑之后,似乎您正在询问expressions

An expression is basically a snippet that has a value . expression基本上是具有value的代码段。 In your example both Jump(3) and var x = 3 are expressions, as both have a value. 在您的示例中, Jump(3)var x = 3都是表达式,因为它们都有一个值。 In other words, Jump(3) is an expression with the value 6 and (x=3) is actually an expression which evaluates to 3 . 换句话说, Jump(3)是一个值为6的表达式,而(x=3)实际上是一个值为3的表达式。

The only difference between the two is that the first expression also assigns a value with the assignment operator (ie = ), while the second expression is "just" a value. 两者之间的唯一区别是,第一个表达式还使用assignment operator (即= )分配了一个值,而第二个表达式“只是”一个值。 For that matter, in your example, the variable x is also an expression that evaluates to 3 . 因此,在您的示例中,变量x也是一个表达式,其结果为3

For more on this subject see MDN - Expressions and operators in Javascript 有关此主题的更多信息,请参见MDN-Javascript中的表达式和运算符

More to the point 更重要的是

This means that when you pass an argument to a function by-value , you're essentially passing the value of the expression. 这意味着,当您将参数传递给函数by-value时 ,实际上是在传递表达式的值。 So in your example, Jump(x) , Jump(3) , Jump((x=3)) and Jump(Jump(1.5)) would all evaluate to 6 . 因此,在您的示例中, Jump(x)Jump(3)Jump((x=3))Jump(Jump(1.5))都将得出6

Naturally, it's much less costly to store the value of common operations in a variable that would be quickly evaluated as an expression, than to have the calculation done each time the expression is evaluated. 自然地,将普通操作的值存储在一个可以快速作为表达式求值的变量中的成本要比每次对表达式求值时都要进行的计算要便宜得多。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM