Obviously this is a non-IE (except advanced IE) topic, however, interested students or together to meet the ECMASCRIPT5 standard getter and setter implementation. In an object, the operation of the properties or methods, usually the most used is read (reference) and write, for example, O.get, this is a read operation, and O.set = 1 is a write operation. In fact, in addition to IE, the latest mainstream browser implementation, the key value of any object can be replaced by getter and setter method, which is called "Accessor properties."
There is no doubt that Getter is responsible for querying the value, it does not take any parameters, the setter is responsible for setting the key value, the value is passed in the form of parameters, in his function body, all return is invalid. Unlike the normal attribute, the memory attribute is not available for both read and write when only the get or set is declared, and when it has only the Getter method, it is only read, and similarly, when it has only setter methods, you will always read undefined. How do I declare object memory properties? The quickest way is to use the syntax of the object literal to write, see the following code:
var oo = { ' virtuous heart ', get Sex () { return ' man '; }}; // Obviously this is not allowed, because Yin heart does not want the outside world to change the fact that he is male, so for sex only set the read-only function oo.sex= ' woman '// result is still man
Interestingly, this overturns our previous understanding that the Function keyword is not used in the definition of a method. In fact here's get or set, you can understand the function in two different states: the Containment side (write), the safe side (read), when a whole is dismembered into different forms, means that we may no longer need to follow the tradition in the manifestation, so we do not use a colon to separate the key and value. So, continue with the example above. How will you become read and write on the basis of memory properties, perhaps the following paragraph will give you an answer:
varOO ={name:' Yin Xin ', Get Sex () {if( This. Sexx) { return This. Sexx; }Else{ return' Man '; }}, set Sex (val) { This. Sexx =Val; }};//Oh, he's so tolerant, even if people change his gender, he also acceptsOo.sex = ' woman '; Console.log (oo.sex);//Result woman
You might think this is superfluous, because we can ignore get and set, directly giving the sex method two permissions. But the reason we took the get and set out alone was to make it clearer to understand ECMAScript5 's more rigorous interpretation of the JavaScript object key-value operation. Of course, in the IE pollution of China, the new mainstream technology is always out of tune, in the actual project development, you may never use get and set, but who can guarantee not later ...
Object accessor properties in ECMAScript5: Getter and setter