I found this piece of code when searching for interview questions a few days ago. After executing it, it felt completely different from what I expected
var a = { n : 1 }; var b = a; a.x = a = {n : 2}; console.log(a.x); console.log(b.x);
The output result is:
undefined
[object Object]
At first I thought the statement should first assign {n : 2} to a, and then assign {n : 2} to a.x;
But that was not the case, so I changed the code and added a few logs
var test; var a = { get test () { console.log("call a get"); return test; }, set test (value) { console.log("call a set"); test = value; } } var test2; var b = { get test2 () { console.log("call b get"); return test2; }, set test2 (value) { console.log("call b set"); test2 = value; } } a.test = { n : 1 }; b.test2 = a.test; console.log("begin"); a.test.x = a.test = {n : 2};
In this way, after begin, it will be clear at a glance what this assignment performs.
This is the log printed when the statement is executed
First a get is triggered, and then a set is triggered.
I guess that the order of execution of this statement is to first take out the variable on the left, and then perform the assignment. (Before executing this statement, first take out the object reference, and then perform the assignment from right to left)
The above is the entire content of this article, I hope you all like it