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

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
主站蜘蛛池模板: 香港| 长顺县| 石城县| 南安市| 台中市| 英德市| 巩义市| 滨州市| 合肥市| 双辽市| 洮南市| 达日县| 德令哈市| 历史| 忻州市| 安龙县| 理塘县| 布拖县| 婺源县| 胶州市| 奈曼旗| 廊坊市| 余庆县| 铅山县| 基隆市| 鄂伦春自治旗| 余干县| 方正县| 阳西县| 元江| 阿尔山市| 扶风县| 馆陶县| 顺平县| 方山县| 临安市| 铜鼓县| 婺源县| 芮城县| 革吉县| 张家界市|