【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
  },
}
相关推荐
困死,根本不会1 小时前
Kivy+Buildozer 打包 APK 踩坑:python-for-android 克隆失败
开发语言·php·kivy
咸鱼2.03 小时前
【java入门到放弃】跨域
java·开发语言
不会写DN3 小时前
Gin 日志体系详解
前端·javascript·gin
冬夜戏雪4 小时前
实习面经记录(十)
java·前端·javascript
skiy4 小时前
java与mysql连接 使用mysql-connector-java连接msql
java·开发语言·mysql
一念春风4 小时前
智能文字识别工具(AI)
开发语言·c#·wpf
桦04 小时前
【C++复习】:继承
开发语言·c++
何仙鸟5 小时前
GarmageSet下载和处理
java·开发语言
wefly20175 小时前
免安装!m3u8live.cn在线 M3U8 播放器,小白也能快速上手
java·开发语言·python·json·php·m3u8·m3u8在线转换
爱学习的程序媛5 小时前
【Web前端】JavaScript设计模式全解析
前端·javascript·设计模式·web