JS continuous variable assignment

Here is the classic case:

Copy the code
There are n = {1};
var b = a;
a.x = a = {n: 2};
console.log(a);
console.log(b); console.log(a.x); console.log(b.x);
Copy the code

 

  We first look at the ordinary continuous assignment, namely: the type of variable assignment is a data type value

    There are a = 3;
    var b = a = 5;
    console.log(a);
    console.log(b);

  In general, the direction of the equal sign is the assignment of right to left, then the above code is equivalent to the following code, then we use the following code to explain the code above:

    var a = 3; // global variable is assigned a 3
    var a = 5; // be reassigned to a case 5
    var b = a; // assigns the value of a global variable b
  console.log (a); // final value is a second value is assigned: 5 
  the console.log (b); // b execution order according to the value of the code is: 5

 

   The above small cases used to initiate, and now we have to analyze this classic case:

Copy the code
var a = {n: 1}; // a first time is assigned, the value is a reference type, to remember when a reference type variable assignment value, change the object by a variable time, the object itself has changed
var b = a; // b is assigned to a, b and therefore is the object n-{:}. 1 
AX = A = {n-: 2};
// This simple case is different from the previous assignment, ax refers to Add a x a property, in the calculation js "." and "=" operator simultaneously, will be executed first. "" calculating
// Accordingly, the order of assignment is changed, give ax is assigned, the assignment to give a
// is the first implementation of: ax = {n: 2} , where a note has not changed, is assigned to a property of x is {n: 2}, a or the n-{: 1}
// go back to my code the first sentence, this assignment behavior, change the {n: 1} this object, i.e. to give it increased property called x
// then perform a = {n: 2}, which is the object is no longer a variable {n: 1}, is reassigned to a new object {n: 2}; console.log (a); // this case A is a natural n-Object {: 2}
the console.log (B); // a secondary assignment did not affect b, b or objects {n: 1}, but Since a prior reassigned to {n: 1} this object, adds a property x, and therefore, when the x b have properties console.log (ax); // {n: 2} x is not the object attribute, the result is undefined console.log (bx); // In summary, the result is {n: 2}   
Copy the code

 Reprinted from: https: //www.cnblogs.com/qiujianmei/archive/2017/07/08/7135428.html

Guess you like

Origin www.cnblogs.com/planetwithpig/p/11703443.html