There are two ways of using setter and getter
1. Set/get
var person = {_name: ', get Name () {return this._name},set name (n) {this._name = n}}//Test person.name//' Person.name = ' john '//' John ', at this time Person._name also became ' John '
2. Object.defineproperty
var person = {}var name = ' Object.defineproperty (person, ' name ', {configurable:true,enumerable:true,get:function ()} {RE Turn name},set:function (n) {name = n}})//test Person.name//Undefind person.name = ' john '//' John ', this time the global name also becomes ' John '
Of course, private variables are usually implemented with setter and getter.
Private variable var person = function () {var _name = ' var _age = 0return {get name () {return _name},set name (n) {_name = n },get age () {return _age},set age (a) {_age = A}}} ()
Or
Private variable var person = function () {var _name = ' var _age = 0var obj = {}object.defineproperty (obj, ' name ', {configurable : True,enumerable:true,get:function () {return _name},set:function (n) {_name = n}}) Object.defineproperty (obj, ' age ', {C Onfigurable:true,enumerable:true,get:function () {return _age},set:function (a) {_age = a}}) return obj} ()
Of course, the best use of setter and getter is to achieve the current popular "two-way binding", mvxx and other libraries. A low-version browser that does not support setter and getter can only be done in polling mode.
ES5 's setter and getter