Javascript中访问器的优先级


本文摘自PHP中文网,作者逆旅行人,侵删。

2021040917385442144.jpg

1.正常使用

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

<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关键字可以删除

               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.访问器属性的优先级高于同名的普通属性

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

<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面试题及答案(大汇总)》

以上就是Javascript中访问器的优先级的详细内容,更多文章请关注木庄网络博客

相关阅读 >>

javascript arguments对象怎么用

javascript如何表示空指针

js中obj是什么

资源合并与压缩的优化方法介绍

javascript怎么修改div内容

javascript怎么弹出对话框

分享 10 个提高 javascript 技能的测验问答

javascript中异步和同步的区别是什么

javascript怎么删除dom

教你用html5画一个馋人的西瓜

更多相关阅读请进入《访问器》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...