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

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
主站蜘蛛池模板: 东丽区| 章丘市| 鹤岗市| 潮安县| 威宁| 通榆县| 古丈县| 邵阳县| 安陆市| 玉山县| 修水县| 桓台县| 邳州市| 白山市| 玛纳斯县| 互助| 宁乡县| 海伦市| 遵义市| 高阳县| 莆田市| 舟曲县| 奉化市| 简阳市| 枝江市| 伊吾县| 双城市| 公安县| 南木林县| 新民市| 安吉县| 正镶白旗| 铜鼓县| 会同县| 尤溪县| 海盐县| 星子县| 永丰县| 缙云县| 剑川县| 绵竹市|