簡單的方法:
let person = {
firstName: 'Jimmy',
lastName: 'Huan',
get fullName(){
return this.firstName + ' ' + this.lastName;
},
set fullName(name){
let words = name.split(' ');
this.firstName = words[0] || '';
this.lastName = words[1] || '';
}
}
官方的方法:
let person = {
firstName: 'Jimmy',
lastName: 'Huan'
}
Object.defineProperty(person, 'fullName', {
get: function(){
return this.firstName + ' ' + this.lastName;
},
set: function(name) {
var words = name.split(' ');
this.firstName = words[0] || '';
this.lastName = words[1] || '';
}
});
console.log(person.fullName);// 'Jimmy Huan'
person.fullName = "Kobe Bryant"; //'Kobe Bryant'
console.log(person.firstName); // 'Kobe'
console.log(person.lastName); // 'Bryant'