Object accessor properties in ECMAScript5: introduction to getters and setters

  • 2020-03-30 04:30:52
  • OfStack

This is obviously an unrelated topic for IE (with the exception of advanced IE), but for those interested, let's take a look at the implementation of getters and setters in the ECMAScript5 standard. In an object, the operation of the properties or methods, usually the most used is to read (reference) and write, such as o.et, which is a read operation, and o.et = 1 is a write operation. In fact, in most recent implementations of major browsers other than ie, the keys of any object can be replaced by getter and setter methods, which are called accessor properties.

Of course, the getter takes care of the query value, which takes no arguments, and the setter takes care of setting the key value, which is passed in the form of an argument. In his body, everything's return is invalid. Unlike normal properties, a storage property that only declares a get or set cannot be read and written at the same time, when it only has getter methods, it is only read-only, and likewise, when it only has setter methods, you will never read undefined. How do I declare object storage properties? The fastest way to do this is to use the syntax of object literals. See the following code:


var oo = {
    name : ' Good heart ',
    get sex(){
        return 'man';
    }
};
//Obviously this is not allowed, because the virtuous mind does not want the outside world to change the fact that he is male, so for sex only set read - only function < br / > oo.sex = 'woman';
console.log(oo.sex); //The result is still man

Interestingly, this overturns our understanding that the function keyword is not used in the method definition. In fact, the get or set here, which you can understand as two different states of function: the inclusive side (write) and the safe side (read), when a whole is dismembered into different forms, means that we may no longer need to follow the tradition of representation, so we don't use a colon to separate the key from the value. So, continue with the example above. How do you become read-write based on the memory properties? Perhaps the following paragraph will give you the answer:


var oo = {
    name : ' Good heart ',
    get sex(){
        if(this.sexx){
            return this.sexx;
        }else{
            return 'man';
        }
    }, set sex(val){
        this.sexx = val;
    }
};
//Oh, he was so tolerant that he accepted people changing his gender oo.sex = 'woman';
console.log(oo.sex); //The woman < br / >


Related articles: