- 物件存取(Object Accessors)
- 別名 getter and setter
- ECMA 5 推出
Getter and Setter
var user = {
name: 'Shawn',
firstName: 'Tseng',
age: 18,
get fullName() {
return this.name + ' ' + this.firstName;
},
set setFirstName(firstName) {
this.firstName = firstName;
}
}
var fullNameNode = document.createTextNode(user.fullName);
var demo1 = document.getElementById('demo1');
demo1.appendChild(fullNameNode);
user.setFirstName = 'Sanada';
var fullNameNode = document.createTextNode(user.firstName);
var demo2 = document.getElementById('demo2');
demo2.appendChild(fullNameNode);
Function vs Getter
get fullName() {
return this.name + ' ' + this.firstName;
}
和
function fullName() {
return this.name + ' ' + this.firstName;
}
有何不同?
使用的時候:
user.fullName; // 語法較輕便
user.fullName();
Object.defineProperty()
Object.defineProperty() 中也可使用 Accessors
沒有留言:
張貼留言