1.正常使用
<script> const product ={ //屬性 data : [ {id :1 ,name : "電腦" , price:5000 , num : 5}, {id :2 ,name : "手機" , price:4000, num : 15}, {id :3 ,name : "相機" , price:6000, num : 25} ], //計算金額(方法) //es6的方法的簡化,將冒號和function關(guān)鍵字可以刪除 getAmounts : function(){ return this.data.reduce((t,c) => (t+=c.price *c.num),0); }, //訪問器屬性,將一個方法包裝成一個屬性 //get:是讀取,也叫讀操作 get total(){ return this.data.reduce((t,c) =>(t+=c.price *c.num),0 ); }, //set:是寫操作 訪問器屬性的寫操作 set setNum(num){ this.data[1].num=num; }, set setPrice(price){ this.data[1].price=price; }, }; console.log(product.getAmounts()); console.log("總金額為:",product.total); product.setPrice=100; console.log("更改后的價格為:",product.data[1].price); </script>
2.訪問器屬性的優(yōu)先級高于同名的普通屬性
<script> let user={ //屬性 data:{name}, //方法 set name(name){ this.data.name=name; }, get name(){ return this.data.name; } } user.name="呵呵"; console.log(user.name); </script>
推薦:《2021年js面試題及答案(大匯總)》