1.在对象中定义get,set访问器属性
<script> var test = { _name:"pmx", _age:18, _born:1990, get name(){ return "name is "+this._name; }, set name(value){ this._name = value; }, get born(){ return this._born; }, set born(value){ this._born = value; }, get age(){ if(this._age > 100){ return new Date().getFullYear() - this.born; }else{ return this._age; } }, set age(value){ this._age = value; } } console.log(test.age); test.age = 2016; console.log(test.age); </script>
2.使用defineProperty给对象添加访问器
<script> var test = { _name:"pmx", _age:18, _born:1990 } Object.defineProperty(test,"name",{ get:function(){ return "name is "+this._name; }, set:function(value){ this._name = value; } }); Object.defineProperties(test,{ age:{ get:function(){ if(this._age > 100){ return new Date().getFullYear() - this.born; }else{ return this._age; } }, set:function(value){ this._age = value; } }, born:{ get:function(){ return this._born; }, set:function(value){ this._born = value; } } }); console.log(test.age); //18 test.age = 2016; console.log(test.age); //26 </script>
3.在类中添加访问器
<script> function test(name,age){ this._name = name; this._age = age; Object.defineProperty(this,"name",{ get:function(){ return "name is "+this._name; } }); } var tt = new test('pmx',26); console.log(tt.name); </script>