简体   繁体   中英

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. Yet I get an error saying that boof cannot be assigned because req.baz is undefined. 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
    a. Let lref be the result of evaluating 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. RTL means that

x = y = 2;

is evaluated as

x = (y = 2);

instead of

(x = y) = 2;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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