简体   繁体   English

Javascript 的评估顺序有更好的解决方案吗?

[英]Is there a better solution for Javascript's order of evaluation?

class foo {
  constructor(req) {
    this.req = req;
  }
  async bar() {
    this.req.baz = {};
    return 1;
  }
}
const req = {};
req.baz.boof = await new foo(req).bar();

I would have thought that JS would eval the right hand side first and req.baz would be an object before the assignment of req.baz.boof was attempted.我会认为 JS 会首先评估右侧,而 req.baz 将是一个对象,然后再尝试分配 req.baz.boof。 Yet I get an error saying that boof cannot be assigned because req.baz is undefined.但是我收到一条错误消息,说无法分配 boof,因为 req.baz 未定义。 I know the code is terrible and should be refactored.我知道代码很糟糕,应该重构。 What fixes it is this:修复它的是这个:

const temp = await new foo(req).bar();
req.baz.boof = temp;

Has anyone seen this before?有没有人见过这个? Is this the best workaround, assuming I can't refactor all the related code?假设我无法重构所有相关代码,这是最好的解决方法吗?

If you look at the specification ,如果你看一下规范

  1. If LeftHandSideExpression is neither an ObjectLiteral nor an ArrayLiteral, then如果 LeftHandSideExpression 既不是 ObjectLiteral 也不是 ArrayLiteral,则
    a.一种。 Let lref be the result of evaluating LeftHandSideExpression.令 lref 为评估 LeftHandSideExpression 的结果。 [...] [...]

Ie compiler/interpreter needs to evaluate left side first to validate and determine the type for the right side expression.即编译器/解释器需要首先评估左侧以验证和确定右侧表达式的类型。

I can't think of a better fix than proposed in the question.我想不出比问题中提出的更好的解决方法。

PS It is not a contradiction to the right-to-left rule. PS 这与从右到左的规则并不矛盾。 RTL means that RTL 意味着

x = y = 2;

is evaluated as被评估为

x = (y = 2);

instead of代替

(x = y) = 2;

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

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