Skip to content

one confused question #6

Description

@miaomiaoji

I love your book so much,it's not only broad also deep,make me think a lot and less confusion.I also preview the 7edition on oreilly,It's also great.I can't wait to own one.But it seems to be take a long time to buy in China.

I have a question to consult you.

var a = {n: 1};
var b = a;
a.x = a = {n: 2};
console.log(a.x);
console.log(b.x);

it is a interview question from internet,and there is a lot of explanations about how to get the result.Most of them just can't convince me.
I have read several times about operator precedence ,order of evaluation part from "the definitive guide", I'm so stuck.

obviously,the key is the third line.
one explanation is "a.x" uses member access(high precedence),so it will evaluate first,it is why "b"and"a" become{n:1;x:undefined},
then the assigment, it has right-to-left associativity,make "a" become a new object{n:2},then assign {n:2} to a.x
Another explanation is order of evaluation,subexpressions will evaluate left-to-right,so "a.x" will evaluate first。

I want to ask some questions

  • the reason about why "a.x" evaluate first,the above explanations are all right?the interpreter(compiler) will use two rules to decide?
  • what happened when "a.x" evaluating?I found something about property accessor ,it says left-hand operand produces a reference,is this mean a new reference which equals to "a.x" ,ecma-262.

maybe it's just because my shortcoming of compiler and interpreter,I really need someone help me .
Thank you!I'm looking forward to your reply.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions