get 將對象屬性綁定到調用查詢該對象屬性時將調用的函數。bash
var obj = {
log: ['a', 'b', 'c'],
get latest() {
if (this.log.length == 0) {
return undefined;
}
return this.log[this.log.length - 1];
}
}
console.log(obj.latest);
// expected output: "c"複製代碼
var expr = 'foo';
var obj = {
get [expr]() { return 'bar'; }
};
console.log(obj.foo); // "bar"複製代碼
set將對象屬性綁定到要調用的函數函數
var language = {
set current(name) {
this.log.push(name);
},
log: []
}
language.current = 'EN';
language.current = 'FA';
console.log(language.log);
// expected output: Array ["EN", "FA"]
//在對象初始化時調用函數複製代碼
set用於賦值,get用於取值。ui