get, set
属性 getter/setter 方法
var man = {
name: 'sunorry',
weibo: '@sunorry',
get age() {
return new Date().getFullYear() - 1990;
},
set age(val) {
console.log('Age can\'t be set to ' + val);
}
};
console.log(man.age); // 25
man.age = 100; // Age can't be set to 100
console.log(man.age); // still 25
更复杂的例子
var a = "abc";
+a; // NaN
var man = {
weibo: '@sunorry',
$age: null, //不想暴露给外部
get age() {
if(this.$age == undefined) {
return new Date().getFullYear() - 1990;
} else {
return this.$age;
}
},
set age(val) {
val = +val; // 尝试转换成数字
if(!isNaN(val) && val > 0 && val < 150) {
this.$age = +val;
} else {
throw new Error('Incorrect val = ' + val);
}
}
}
console.log(man.age); // 27
man.age = 100;
console.log(man.age); // 100
man.age = 'abc'; // error: Incorrect val = NaN
get / set 与原型链
function foo() {}
Object.defineProperty(foo.prototype, 'z', {
get: function() {
return 1;
}
});
var obj = new foo();
obj.z; // 1
obj.z = 10;
obj.z; // still 1
Object.defineProperty(obj, 'z', {
value: 100,
configurable: true
});
obj.z; // 100;
delete obj.z;
obj.z; // back to 1
var o = {};
Object.defineProperty(o, 'x', {
value: 1
}); // writeable=false, configurable=false
var obj = Object.create(o);
obj.x; // 1
obj.x = 200;
obj.x; // still 1, can't change it
Object.defineProperty(obj, 'x', {
writeable: true,
configurable: true,
value: 100
});
obj.x; // 100
obj.x = 500;
obj.x; // 500
网友评论