function Person(name) {
this.name = name;
this.flag = 0;
Object.defineProperty(this, ‘name‘, {
get: function() { return name;},
set: function(newName) {
if (this.flag) {
name = newName;
this.flag = 0;
}
return name;
}
});
this.setName = function(newName) {
this.flag = 1;
this.name = newName;
}
};
var manx = new Person(‘manx‘);
console.log(manx.name); // manx
manx.name = "bob";
console.log(manx.name); // manx
manx.setName(‘jack‘);
console.log(manx.name); // ‘jack‘
原文:http://www.cnblogs.com/ax-null/p/7112809.html