Setter and getter

Setters and getters are the third person between variables and functions. They can both store variables and execute functions.

var obj = {
            a:1._c:0.// Store values with temporary variables
            b:function(){},set c(value) {// There is only one argument
                this._c=value;
            },
            get c() {// No arguments are allowed
                return this._c;
            }
        }
        obj.c = 10;// Use set with attribute as value
        console.log(obj.c)// Get with get
Copy the code

Set can directly modify variables, one and only one parameter, the parameter is the value of your external modified incoming, he was put in a temporary variable to store the temporary variable does not generally exposed to the external, as long as when you change this value, the function of his will automatically call set, so can be written in the set function to convenient we use. If only the set method is written to an object, the value is an attribute and cannot be retrieved.

Get can fetch the value directly from a temporary variable. The get method is not allowed to write any arguments. If the only method in an object is get, this property is equivalent to a read-only property.

Set and GET are used as properties in objects and can be called directly.

The main disadvantage of set and GET is that when an array or object is used as a temporary variable, the set will not be executed if the contents of the array or object change but the reference address does not change. The set assumes that the reference address has not changed, so it cannot trigger the set function even if the contents change. Set can only be executed if a new array or object is externally defined and the variable reference address is changed each time it is passed in.

Set and GET are great, but they have compatibility issues. They only support modern browsers.

var div=document.querySelector("div");
var obj={
      _arr: [].// Array as temporary variable
      set arr(value) {if(!Array.isArray(value)) return;
       if(this._arr.join()===value.join()) return;
       div.innerHTML="";
        for(var i=0; i<value.length; i++){let ball=Utils.ce("div", {width:"50px".height:"50px".backgroundColor:"red".color:"#FFFFFF".textAlign:"center".lineHeight:"50px".borderRadius:"50px".float:"left"
                    },div);
                    ball.textContent=value[i];
                }
                this._arr=value;
            },
            get arr() {return this._arr; }}var a=[];
        var t=0;
       setInterval(animation,2000);

       function animation(){
          t++;
          a.push(t);
          obj.arr=a;// It is useless to add to arR directly without reassigning to trigger set
       } 
Copy the code