Home > Web Front-end > JS Tutorial > body text

javascript continuous assignment problem_javascript skills

WBOY
Release: 2016-05-16 15:50:50
Original
1207 people have browsed it

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);

Copy after login

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};

Copy after login

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

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template