官术网_书友最值得收藏!

Getters and setters

To assign a value to a property of a JavaScript object is as simple as:

var myObj = {
  prop: 'Hello'
}

To retrieve it is just as simple:

myObj.prop

There's no trick here. The point I want to make though, is that we can replace this normal assignment/retrieval mechanism of an object through use ofgetters and setters. These are special functions that allow custom logic for getting or setting the property's value.

Getters and setters are especially useful when one property's value is determined by another. Here's an example:

var person = {
  firstName: 'Abraham',
  lastName: 'Lincoln',
  get fullName() {
    return this.firstName + ' ' + this.lastName;
  },
  set fullName(name) {
    var words = name.toString().split(' ');
    this.firstName = words[0] || '';
    this.lastName = words[1] || '';
  }
}

Thegetandsetfunctions of thefullNamepropertyare invoked whenever we attempt a normal assignment/retrieval of its value:

console.log(person.fullName); // Abraham Lincoln
person.fullName = 'George Washington';
console.log(person.firstName); // George
console.log(person.lastName) // Washington
主站蜘蛛池模板: 泾川县| 沂水县| 临夏县| 安新县| 顺义区| 阿坝| 马尔康县| 丰城市| 土默特左旗| 鄂尔多斯市| 衡阳县| 教育| 麻城市| 林周县| 桐乡市| 惠东县| 诏安县| 两当县| 芷江| 涿鹿县| 响水县| 资兴市| 祁东县| 邵东县| 宜章县| 龙里县| 文山县| 沾益县| 台江县| 攀枝花市| 福州市| 绥中县| 长岛县| 个旧市| 莱芜市| 吉木萨尔县| 景泰县| 眉山市| 明溪县| 刚察县| 吉水县|