ES5 's setter and getter

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.