当前位置: 首页 > news >正文

【JS】访问器成员

前言

如下例,有一商品对象,其中属性分别为单价和数量以及一个用于计算总价的方法,需要通过 product.getTotal() 获得总价,也可以使用访问器成员getter控制属性读写逻辑,通过 product.total 的方式获取总价,提高可读性。

const product = {name: "iphone",price: 13999,count: 3,getTotal: function () {return this.price * this.count},
}

ES5

function Product(name, price, count) {this.name = namethis.price = pricethis.count = count
}
Object.defineProperty(Product.prototype, "total", {get: function () {return this.price * this.count},
})

ES6

class Product {constructor(name, price, count) {this.name = namethis.price = pricethis.count = count}get total() {return this.price * this.count}
}

Object

const p = {name: "iphone",price: 13999,count: 3,get total() {return this.price * this.count},
}
http://www.lryc.cn/news/451587.html

相关文章:

  • 五子棋双人对战项目(3)——匹配模块
  • 开源软件简介
  • Bruno:拥有 11.2k star 的免费开源 API 测试工具
  • C动态内存管理
  • 系列二、案例实操
  • Python编码系列—Python状态模式:轻松管理对象状态的变化
  • 卸载WSL(Ubuntu),卸载linux
  • Lumerical脚本语言-系统(System)
  • QT 界面编程中使用协程
  • macOS 开发环境配置与应用开发
  • 第13讲 实践:设计SLAM系统
  • NeRF2: Neural Radio-Frequency Radiance Fields 笔记
  • 以太网交换安全:MAC地址表安全
  • CSS综合页布面局案例
  • 低代码可视化-UniApp二维码可视化-代码生成器
  • Electron 使用 Nodemon 配置自动重启
  • JVM和GC监控技术
  • Android中级控件
  • WebSocket消息防丢ACK和心跳机制对信息安全性的作用及实现方法
  • 生信初学者教程(二十二):Boruta+RF筛选候选标记物
  • JVM Class类文件结构
  • 解决 GitHub 文件大小限制的问题
  • wordpress源码资源站整站打包32GB数据,含6.7W条资源数据
  • 金融领域的人工智能——Palmyra-Fin 如何重新定义市场分析
  • STL--string类
  • iptables 的NDAT报错bash: 9000: command not forward
  • 快速了解:MySQL InnoDB和MyISAM的区别
  • TI DSP TMS320F280025 Note14:模数转换器ADC原理分析与应用
  • 【C++前缀和】2845. 统计趣味子数组的数目|2073
  • C++入门基础 (超详解)