简体   繁体   English

JavaScript-可以在变量声明期间定义先前声明的对象的属性吗?

[英]JavaScript - Is it okay to define a property of a previously declared object during a variable declaration?

Is it common practice (or at least syntactically valid across browsers and implementations of JS) to abuse RTL associativity of assignment operators so that one can define two variables (with the first being an object) so that the second is assigned to a (newly) named property of that object which is itself assigned to another value, so that a SyntaxError() is not generated? 滥用赋值运算符的RTL关联性是常见的做法(或至少在语法上在跨浏览器和JS的实现上至少在语法上有效),以便一个可以定义两个变量(第一个为对象),以便第二个分配给(新)该对象的命名属性,该对象本身已分配给另一个值,因此不会生成SyntaxError()?

I know that sounds complicated, but here is the code: 我知道这听起来很复杂,但这是代码:

var x = {}, y = x.l = 9; // generates no errors
console.log(x.l, y); // 9 9

Since: 以来:

var t = {}, t.l = 9; // Syntax Error, no doubt because t is already defined

The line: 该行:

var x = {}, y = x.l = 9;

effectively becomes: 有效地变为:

var x = {};
var y = x.l = 9;

which is processed as: 处理为:

// Parse phase
var x; // assigned the value undefined
var y; // assigned the value undefined

// Execution phase
x = {};
x.l = 9;
y = x.l;

Noting that in an assignment expression, the value on the right is assigned to the expression on the left. 注意,在赋值表达式中,右边的值分配给左边的表达式。 Compound assignments are evaluated left to right, but assigned from right to left, hence xl = 9 is assigned before y = xl , even though it's on the right. 复合分配是从左到右评估的 ,但是从右到左分配的 ,因此xl = 9会在y = xl之前分配,即使它在右侧。

Now try that with the second example: 现在,使用第二个示例进行尝试:

var t = {}, t.l = 9;

becomes: 变为:

// Parse phase
var t;   // assigned the value undefined
var t.l; // syntax error, stop

The var keyword at the start of a statement means the next thing must be a valid identifier. 语句开头的var关键字表示下一件事必须是有效的标识符。 tl is not a valid identifier (it can only be interpreted as an identifier followed by a dot property accessor), so that's it. tl不是有效的标识符(只能解释为标识符,后跟点属性访问器),仅此而已。 Everything stops. 一切都停止了。

You need to use the semicolon - that's what the error says the parser expects: 您需要使用分号-这就是解析器期望的错误:

 var t = {}; tl = 9; console.log(t); 

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

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