【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
  },
}
相关推荐
自由的好好干活4 分钟前
使用Qoder编写ztdaq的C#跨平台示例2
开发语言·c#·ai编程
赵财猫._.2 小时前
Native API开发:C++与ArkTS混合编程实战
开发语言·c++·harmonyos
鱼锦0.02 小时前
在vue2中主页面怎么给子页面传递数据
前端·javascript·html
普通网友2 小时前
基于C++的操作系统开发
开发语言·c++·算法
狂团商城小师妹3 小时前
JAVA外卖霸王餐CPS优惠CPS平台自主发布小程序+公众号霸王餐源码
java·开发语言·小程序
2501_941111343 小时前
C++中的策略模式高级应用
开发语言·c++·算法
心软小念4 小时前
用Python requests库玩转接口自动化测试!测试工程师的实战秘籍
java·开发语言·python
sanggou5 小时前
【Python爬虫】手把手教你从零开始写爬虫,小白也能轻松学会!(附完整源码)
开发语言·爬虫·python
普通网友5 小时前
C++与Qt图形开发
开发语言·c++·算法
!win !5 小时前
前端跨标签页通信方案(下)
前端·javascript