首页 > 代码库 > JS之访问器
JS之访问器
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>
JS之访问器
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。