<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>getter与setter——音乐播放器例子 </title> <style type="text/css"> div{ font-size: 299x; } </style> </head> <body> <div id="app"> <div class="play-btn"></div> </div>
<script> class AudioPlayer{ constructor(){ this._status = 0; //要修改的属性 this.status = 0; //程序初始化时候的值 this.init(); } init(){ const audio = new Audio(); audio.src = '...'; audio.oncanplay = () =>{ audio.play(); this.status = 1; } } get status(){ return this._status; } set status(val){ const STATUS_MAP = { 0:'暂停', 1:'播放', 2:'加载中' }; document.querySelector('#app .play-btn').innerText = STATUS_MAP[val]; this._status = val; } } const audio = new AudioPlayer(); </script> </body> </html>
输入出生年份并自动计算当前年龄:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> </head> <body> <script type="text/javascript"> let year = prompt("请输入年份"); // 补充代码 //使用变量接收输入的年份 //定义一个类,设置默认的年龄为18 class Age{ constructor(){ this.age='', this._age='18' } get age(){ return this._age; } set age(val){ if(val.length !== 4){ this._age = 18 }else{ let date = new Date(); //当前日期 let curYear = date.getFullYear(); //返回一个表示年份的四位数字 this._age = curYear - val; } } } const agee = new Age(); agee.age= year; document.write(agee.age) </script> </body> </html>