var man={
name:'dudu',
weibo:'dudu',
get age(){
return new Date().getFullYear() - 1988;
},
set age(val){
console.log( ' Age can't be set to '+ val)
}
}
console.log(man.age) //27
man.age=100 // Age can't be set to 100
console.log(man.age ) //27
var man={
name:'dudu',
$age:null,
get age(){
//判断是否是null和ndefined ==
if(this.$age==undefined){
return new Date().getFullYear() - 1988;
}else{
return this.$age;
}
},
set age(val){
//js使用'val === +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
mag.age='abc' //error:Incorrect val =NaN
原型链与 get set
function foo(){
Object.definePropertyt(foo.prototype,'z',
{ get : function(){
return 1;
}}
)
}
var obj = new foo()
obj.z // 1
obj.z=10;
obj.z //1
Object.defineProperty(obj,'z',
{value:100 ,confingurable:true});
obj.z;//100
delete obj.z;
obj.z;//back to 1
}
var o={}
Object.defineProperty(o,'x',{value:1}); //writable:false,configurable:false
var obj=Object.create(o)
obj.x; //1
obj.x=200;
obj.x; // 1 不能更改
Object.defineProperty(obj,'x',{writable:true,configurable:true,value:100})
obj.x;//100
obj.x=700;
obj.x; //700