问题描述
将调用内部 GetValue(expr)
,但总是返回 undefined
,无论是什么值或表达式。
The void operator in JavaScript will call the internal GetValue(expr)
, but always return undefined
, regardless of what value or expressions are.
规范说:
生产 UnaryExpression:void UnaryExpression 评估如下:
- 让expr成为评估 UnaryExpression 的结果。
- 调用
GetValue(expr)
。 - 返回undefined。
- Let expr be the result of evaluating UnaryExpression.
- Call
GetValue(expr)
. - Return undefined.
必须调用GetValue,即使其值为没有使用,因为它可能有可观察到的副作用。
GetValue must be called even though its value is not used because it may have observable side-effects.
我的问题是,为什么?会发生什么样的可观察副作用?我们能否证明void如何改变程序流程,并讨论如果我们没有运行 GetValue
会发生什么?
My question is, why? What sort of observable side-effects could happen? Can we demonstrate how void might alter program flow, and discuss what would happen if we didn't run GetValue
?
推荐答案
如果你正在编写一个没有副作用的程序,那么总是返回undefined的函数没有用,因为它不会将有用的信息返回给调用者。在这种情况下,如果你总是知道你会得到什么,你也可以根本不打电话。
If you're writing a program with no side effects, then a function that always returns undefined isn't helpful because it does not return useful information back to the caller. In that case, you might as well not call the function at all if you always know what you'll be getting back.
但是,如果一种语言有副作用 ,即使返回undefined的函数仍然可以在编程上有用。 副作用是某些效果的技术术语,它不是函数返回值的一部分。作为一个具体的例子,改变DOM是一种不会计算并返回有用值的副作用,但您仍然希望DOM树的状态发生变异。播放声音也是一种副作用。
However, if a language has "side effects", even functions that return undefined can still be programatically useful. "Side-effects" is a technical term for some effect that's not a part of the return value of a function. As a concrete example, mutating the DOM is a side effect that doesn't compute and return a useful value, but you still want the state of your DOM tree to mutate. Playing a sound is also a side effect.
作为旁注, void 可能很有用,因为从语法上讲,它强制表达式上下文,这样就可以明确地表达函数表达式值之类的东西。例如
As a side note, void can be useful since, grammatically, it forces an expression context, so that things like function expression values can be expressed unambiguously. e.g.
void function(){alert('hi')}()
这篇关于为什么void运算符在始终求值为undefined时会调用GetValue(expr)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!