Why does the data in VUE need to return

                                                                                     Why does the data in VUE need to return

Questions to ask in every interview

              directly on the code

 var obj={
        name:"zhangsan",
        age:20
      }
      var a=obj;
      var b=obj;
      a.age=18
      console.log(a,b)   // {name: "zhangsan", age: 18} {name: "zhangsan", age: 18}

You can easily find that when I modify this value directly, both a and b are modified. When this is an assignment object in js, only the address of the object is assigned, and the value in it is not deep copied.

 Why is this? Because Object in JS is a reference data type, when I define variables a and b equal to obj object, I just make a shallow copy of the object. The value of a and b is actually just an address (that is, the stack) pointing to the obj object.
When I am modifying a.age, JS will find the value in the heap space of the obj object through the path of variable a and modify it. . . When I output a and b, I use this path in the stack space to find the heap

Next, let's implement it again, using the return method

var data=function(){
        return{
          name:"zhangsan",
          age:20
        }
      }
      var a=data();
      var b=data();
      a.age=18
      console.log(a,b)   //{name: "zhangsan", age: 18} {name: "zhangsan", age: 20}

This is why? Because only functions have scope in JS, when data is a function, each component instance has its own scope, and each instance is independent of each other and will not affect each other! ! Learned again. He also explained his doubts and shared them with everyone.

If you have learned, please help to like, comment, forward, bookmark, or reward, thank you.

Guess you like

Origin blog.csdn.net/qq_36131502/article/details/107961903