使用访问器属性模拟java中的私有变量
2016-05-15 00:00
387 查看
[code=plain]<script> "use strict";//注意,一定要写严格模式 function Emp(id,age){ this.id=id; Object.defineProperty(this,"age",{ get:function(){ return age; }, set:function(value){ if(value<18||value>65){ throw new Error("年龄不符合要求"); } age=value; } }); Object.seal(this);//密封 } var emp=new Emp(1001,24); console.log(emp); console.log(emp.age);//24 emp.age++; console.log(emp.age);//25 delete emp.id;//Cannot delete property 'id' of #<Emp> </script>