JavaScript Accesor属性(获取和设置)
示例
将属性视为两个函数的组合,一个函数从属性中获取值,另一个函数在其中设置值。
该get属性描述的属性是一个将被调用来检索属性的值的功能。
该set属性也是一个函数,当为属性分配了值时,将调用该函数,并将新值作为参数传递。
你不能指定一个value或writable 一个描述符有get或set
var person = { name: "John", surname: "Doe"};
Object.defineProperty(person, 'fullName', {
get: function () {
returnthis.name+ " " + this.surname;
},
set: function (value) {
[this.name, this.surname] = value.split(" ");
}
});
console.log(person.fullName); // -> "John Doe"
person.surname = "Hill";
console.log(person.fullName); // -> "John Hill"
person.fullName = "Mary Jones";
console.log(person.name) // -> "Mary"