在 JavaScript 中,如果将某种表达式放在赋值表达式的左侧,引擎将抛出 ReferenceError。例如,
// 'this' on the left side
this = window; // ReferenceError: Invalid left-hand side in assignment
或
// function call expression on the left side
var a;
var fn = function() {return a};
a === fn(); // true
a = 1; // 1
fn() = 5; // ReferenceError: Invalid left-hand side in assignment
或
var a;
a = 1; // 1
(a) = 2; // 2
(1, a) = 3; // ReferenceError: Invalid left-hand side in assignment
我的问题是:
JavaScript是不是和C一样有左值和右值的概念?
为什么函数调用表达式不能出现在赋值表达式的左边?在上面的例子中,由于
a === fn()
,a = 5
和fn() = 5
有什么区别。我知道 ES5 规范要求这样做,但为什么要这样设计?
最佳答案
根据specification of assignments , 以下表达式作为赋值的目标无效:
this
Literal
ArrayLiteral
ObjectLiteral
FunctionExpression
ClassExpression
GeneratorExpression
RegularExpressionLiteral
TemplateLiteral
例如,下面的赋值也是无效的:
this = "bar"; // this
"foo" = "bar"; // Literal
/foo/ = "bar"; // RegularExpressionLiteral
["foo"] = "bar"; // ArrayLiteral
关于javascript - JavaScript有左值和右值的概念吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30770292/