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

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
主站蜘蛛池模板: 和顺县| 子洲县| 武功县| 扶风县| 德令哈市| 扎鲁特旗| 大邑县| 巴中市| 沁源县| 雷波县| 连州市| 华安县| 石屏县| 藁城市| 和田市| 祁门县| 霍州市| 信宜市| 汉中市| 孟津县| 南靖县| 乳山市| 南阳市| 长海县| 永川市| 琼中| 贵溪市| 平果县| 思茅市| 铜川市| 霍林郭勒市| 汶川县| 名山县| 乐至县| 东兰县| 南充市| 红原县| 镇原县| 香格里拉县| 保亭| 从江县|