为了扩展这个问题,我希望这个陈述是可能的:
declare("Hello") = bindVal("World")
其中 declare
和 bindVal
都是执行以下操作的函数:
function declare(p){ return window[p] }
function bindVal(x){ return x }
这里的要点是 declare
运行一些操作并有一些副作用。但就我而言,声明不必返回任何内容。不过,如果它返回一个等待赋值的“悬空”变量,那将是最理想的。
现在在控制台中运行此表达式会引发错误:
ReferenceError: Invalid left-hand side in assignment
所以我的问题是:我可以用函数 declare
做一些奇特的事情,这样我的语句就可以实现吗?在我看来,这是如何评估左侧和右侧的顺序:
declare("Hello") = bindVal("world")
window.Hello = bindVal("world")
window.Hello = world
总而言之,左侧先于右侧进行全面评估。
最佳答案
an assignment的左侧部分must be a reference和 you can't return a reference from a function :
No built-in ECMAScript function defined by this specification returns a reference and there is no provision for a user-defined function to return a reference.
所以你必须这样做。
您可以返回要更改的变量的名称,但最简洁的方法是返回执行赋值的函数:
function declare(n){
return function(v){ window[n]=v }
}
declare("Hello")(bindVal("World"));
关于javascript - 是否可以在评估右侧之前强制 `=` 的左侧完全评估为引用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19434885/