JavaScript, the object in the get and set methods

1: get the syntax of object attributes bound to the function will be called when the query property.

2: set when attempting to set a property, set the syntax to bind object properties to the function to call.

 3: an example of name data attribute; age properties after the get, set is an access attributes, access attributes: when the external js to age assignment take time setter function, when the external js acquired age go getter function, setter and getter functions are hidden, we will take back the write function in age.

a) Error example, recursive error Hassan

 

        each person = {
            name: "zhangsan",
            age: 18,
            get age() {
                return this.age;
            },
        };
        console.log (person.age); // error t.html: 23 Uncaught RangeError: Maximum call stack size exceeded; "call stack exceeds the maximum size"
An error

t.html:23 Uncaught RangeError: Maximum call stack size exceeded
at Object.get age [as age] (t.html:23)
at Object.get age [as age] (t.html:24)
at Object.get age [as age] (t.html:24)
at Object.get age [as age] (t.html:24)
at Object.get age [as age] (t.html:24)
at Object.get age [as age] (t.html:24)
at Object.get age [as age] (t.html:24)
at Object.get age [as age] (t.html:24)
at Object.get age [as age] (t.html:24)
at Object.get age [as age] (t.html:24)

Cause: This error occurs most common causes are: somewhere in the code, you are calling a function, which in turn calls another function, and so on, until the call stack limit. It almost always has a recursive function because the basic situation of unmet

b): Example correct

   
        each person = {
            _name: "zhangsan",
            _age: 18,
            get age() {
                return this._age;
            },
            set age(value) {
                console.log('set')
                if (value > 100) {
                    console.log (Age input `$ {value} is greater than 100, incorrect ')
                } else {
                    this._age = value;
                }
            }
        };
        person.age = 111;
        console.log (person.age) // set; older input 111 is greater than 100, it is not correct; 18
        person.age = 10;
        console.log(person.age)   //set; 10
//////////////////////////////
        each person = {
            name: "zhangsan",
            get age() {
                return 18
            },
            set age(value) {
                console.log('set')
                if (value > 100) {
                    console.log (Age input `$ {value} is greater than 100, incorrect ')
                } else {
                    this.age = value;
                }
            }
        };
        console.log(person.age)  //18

 

Guess you like

Origin www.cnblogs.com/yt0817/p/12449116.html