Home > Article > Web Front-end > Classic case of continuous assignment in js
Today I encountered a classic case of continuous assignment. The answers given by netizens are also varied, which seems a bit cumbersome. Let me share my opinions.
In order to take care of beginners, I used the simplest, easy-to-understand and even somewhat verbose words to explain my understanding of this case. It is actually not difficult.
The following is this classic case:
<span style="font-size: 14px"><span style="color: #0000ff">var</span> a = {n: 1<span style="color: #000000">};</span><span style="color: #0000ff">var</span> b =<span style="color: #000000"> a; a.x </span>= a = {n: 2<span style="color: #000000">};<br>console.log(a);<br>console.log(b); console.log(a.x); console.log(b.x); <br></span></span>
Let’s take a look at ordinary continuous Assignment, that is: the type of variable assignment is the data type value
var a=3;var b=a=5; console.log(a); console.log(b);
Generally speaking, the direction of equal sign assignment is from right to left, then the above code Equivalent to the following code, then we will use the following code to explain the above code:
<span style="font-size: 14px"> <span style="color: #0000ff">var</span> a=3<span style="color: #000000">; //全局变量a被赋值为3</span><span style="color: #0000ff">var</span> a=5<span style="color: #000000">; //此时a被重新赋值为5</span><span style="color: #0000ff">var</span> b=<span style="color: #000000">a; //将a的值赋给全局变量b<br></span></span>
<span style="font-size: 14px"> console.log(a);//a最终的值就是第二次被赋的值:5<br> console.log(b);//按照代码执行顺序b的值也是:5</span>
The above small case It is used to attract new ideas. Now let’s analyze this classic case:
<span style="font-size: 14px"><span style="color: #0000ff">var</span> a = {n: 1<span style="color: #000000">};//a第一次被赋值,是一个引用类型值,请记得变量赋值为引用类型值的时候,通过变量改变这个对象的时候,对象本身也发生了变化</span><span style="color: #0000ff">var</span> b =<span style="color: #000000"> a;//b被赋值为a,因此b就是对象{n:1}<br>a.x </span>= a = {n: 2</span><span style="color: #000000"><span style="font-size: 14px">};</span><br><span style="font-size: 14px">//这个赋值与之前的简单案例有所不同,a.x指的是给a添加一个x属性,在js的运算中“.”和"="运算符同时出现,会先执行"."运算</span><br><span style="font-size: 14px">//因此,赋值顺序被改变了,是先给a.x赋值,再给a赋值</span><br><span style="font-size: 14px">//就是先执行:a.x={n:2},注意这里a并未改变,是给a的x属性赋值为{n:2},a还是{n:1}<br>//再回到我代码中的第一句话,这个赋值行为,改变了{n:1}这个对象,即给它增加了名为x的属性</span><br><span style="font-size: 14px">//再执行a={n:2},这是变量a不再是对象{n:1},而被重新赋值为一个新的对象{n:2}; console.log(a);//自然此时a是对象{n:2}</span><br><span style="font-size: 14px">console.log(b);//a的二次赋值,并没有影响b,b还是对象{n:1},但是由于a在重新赋值之前,给{n:1}这个对象,增加了一个x属性,因此,这时的b已经有了x属性 console.log(a.x);//{n:2}对象没有x属性,所以结果是undefined console.log(b.x);//综上所述,这个结果是{n:2} </span> </span>
I don’t know if you understand?
The above is the detailed content of Classic case of continuous assignment in js. For more information, please follow other related articles on the PHP Chinese website!