Home  >  Article  >  Web Front-end  >  Priority of accessors in Javascript

Priority of accessors in Javascript

autoload
autoloadOriginal
2021-04-09 17:57:341806browse

Priority of accessors in Javascript

1. Normal use

 <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. Accessor attribute The priority is higher than the ordinary attribute with the same name

  <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>

Recommended: "2021 js interview questions and answers (large summary)"

The above is the detailed content of Priority of accessors in Javascript. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn