// syntaxlet obj = {getpropName() {// getter, the code executed on getting obj.propName },setpropName(value) {// setter, the code executed on setting obj.propName = value }};// 用已有的資料添加 fullName 屬性let user = { name:"John", surname:"Smith",getfullName() {return`${this.name}${this.surname}`; }};alert(user.fullName); // John Smith// 不用函式的方式呼叫 get,使用一般屬性呼叫得到值// 改變 fullName 的值,要用 setlet user = { name:"John", surname:"Smith",getfullName() {return`${this.name}${this.surname}`; },setfullName(value) { [this.name,this.surname] =value.split(" "); }};// set fullName is executed with the given value.user.fullName ="Alice Cooper";alert(user.name); // Alicealert(user.surname); // Cooper// 一個屬性只能有一個類型,如果屬性用 get、set 定義,就不是資料屬性。// If there’s a getter – we can read object.prop, otherwise we can’t.// If there’s a setter – we can set object.prop=..., otherwise we can’t.// 我們不能刪除訪問屬性
Accessor descriptors
訪問屬性沒有 value、writable。
get – a function without arguments, that works when a property is read,
set – a function with one argument, that is called when the property is set,
enumerable – same as for data properties,
configurable – same as for data properties.
let user = { name:"John", surname:"Smith"};Object.defineProperty(user,'fullName', {get() {return`${this.name}${this.surname}`; },set(value) { [this.name,this.surname] =value.split(" "); }});alert(user.fullName); // John Smithfor(let key in user) alert(key); // name, surname// Error: Invalid property descriptor.Object.defineProperty({},'prop', {get() {return1 }, value:2});
Smarter getters/setters
let user = {getname() {returnthis._name; },setname(value) {if (value.length<4) {alert("Name is too short, need at least 4 characters");return; }this._name = value; }};user.name ="Pete";alert(user.name); // Peteuser.name =""; // Name is too short...
Using for compatibility
// 原本儲存了 name、age 屬性functionUser(name, age) {this.name = name;this.age = age;}let john =newUser("John",25);alert( john.age ); // 25// 現在改儲存 name、birthday 屬性functionUser(name, birthday) {this.name = name;this.birthday = birthday;}let john =newUser("John",newDate(1992,6,1));// 舊的 age 屬性可以做改寫,符合我們的使用functionUser(name, birthday) {this.name = name;this.birthday = birthday;// age is calculated from the current date and birthdayObject.defineProperty(this,"age", {get() {let todayYear =newDate().getFullYear();return todayYear -this.birthday.getFullYear(); } });}let john =newUser("John",newDate(1992,6,1));alert( john.birthday ); // birthday is availablealert( john.age ); // ...as well as the age