js attention by a method that returns an object point

Question: js return a literal objects by means of a good return and literal objects has been defined in advance there a difference?

Answer: There are

Let's look at the first case , fun1 method returns a literal object definition did not advance, and then returns three object by calling the method, namely obj1, obj2, obj3, then I modified the object obj2 age method, print obj1 , obj2, obj3, what are the attributes of age?

1  // first case: 
2          function fun1 () {
 . 3  
. 4              return {
 . 5                  the uname: `ash`,
 . 6                  Age: 18 is
 . 7              }
 . 8              // here returns a literal object 
9              // every time it does not return the same target address, a change of the age attribute obj2, obj1, obj3, age property is not influential 
10          }
 . 11          OBJ1 = fun1 ();
 12 is          obj2 = fun1 ();
 13 is          OBJ3 = fun1 ();
 14          obj2.age = 16 ;
 15          the console.log (obj1.age);
 16         console.log(obj2.age);
17         console.log(obj3.age);

Print Results:

obj1.age = 18   

obj2.age = 16  

 obj3.age = 18

Why is there such a household result? Because every time fun1 return address is not the same object, so changing the age attribute of obj2, obj1, obj3, age is not going to affect property

 

Look at the second case , I define good obj3, return the object by fun2 () method, and now I call fun2 method returns obj21 obj22 obj23 objects, modify the attributes obj22 target age is 16, are printed obj21 obj22 obj23 object age property

result:
obj21.age = 18 
obj21.age = 16 
obj21.age = 18
1  // second case: 
2          var OBJ3 = {
 . 3              the uname: `ash`,
 . 4              Age: 18 is
 . 5          };
 . 6  
. 7          function fun2 () {
 . 8              return obj2;
 . 9          }
 10          Obj21 = fun2 ();
 . 11          Obj22 = fun2 ();
 12 is          obj23 = fun2 ();
 13 is          obj2.age = 16 ;
 14          the console.log (obj21.age);
 15          the console.log (obj22.age);
 16         console.log(obj23.age);

Why is there such a result?

Because there has been a return defined objects, each of the return memory address is the same, so long as the properties mentioned objects are changed, by this method returns the object property will change

 

Guess you like

Origin www.cnblogs.com/chq1234/p/11693031.html