【JS】访问器成员

前言

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

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

ES5

javascript 复制代码
function Product(name, price, count) {
  this.name = name
  this.price = price
  this.count = count
}
Object.defineProperty(Product.prototype, "total", {
  get: function () {
    return this.price * this.count
  },
})

ES6

javascript 复制代码
class Product {
  constructor(name, price, count) {
    this.name = name
    this.price = price
    this.count = count
  }
  get total() {
    return this.price * this.count
  }
}

Object

javascript 复制代码
const p = {
  name: "iphone",
  price: 13999,
  count: 3,
  get total() {
    return this.price * this.count
  },
}
相关推荐
灵感__idea2 小时前
Hello 算法:贪心的世界
前端·javascript·算法
小成202303202653 小时前
Linux高级02
linux·开发语言
知行合一。。。3 小时前
Python--04--数据容器(总结)
开发语言·python
咸鱼2.03 小时前
【java入门到放弃】需要背诵
java·开发语言
ZK_H3 小时前
嵌入式c语言——关键字其6
c语言·开发语言·计算机网络·面试·职场和发展
A.A呐3 小时前
【C++第二十九章】IO流
开发语言·c++
椰猫子3 小时前
Java:异常(exception)
java·开发语言
lifewange4 小时前
pytest-类中测试方法、多文件批量执行
开发语言·python·pytest
cmpxr_4 小时前
【C】原码和补码以及环形坐标取模算法
c语言·开发语言·算法
2401_827499994 小时前
python项目实战09-AI智能伴侣(ai_partner_5-6)
开发语言·python