<!doctype html>
<html>
<head>
<title>标题</title>
<meta charset="utf-8">
<script>
var emp={
id:1001,
name:"eric"
};
//定义访问器属性age
(function(_age){
Object.defineProperty(emp,"age",{
get:function(){//取值时自动调用
return _age;
},
set:function(val){
if(val<18||val>65){
throw new RangeError(
"age must between 18 and 65"
);
}
_age=val;
}
});
})(25);
console.log(emp.age);
emp.age=30;
console.log(emp.age);
emp.age++;//31
try{
emp.age=15;//set(15)
}catch(err){
console.log(String(err));
}finally{
console.log(emp.age);
}
</script>
</head>
<body>
</body>
</html>
javascript面向对象(八)
最新推荐文章于 2024-01-07 18:00:00 发布