【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
  },
}
相关推荐
Tony Bai4 小时前
高并发后端:坚守 Go,还是拥抱 Rust?
开发语言·后端·golang·rust
怕浪猫4 小时前
第一章 JSX 增强特性与函数组件入门
前端·javascript·react.js
wjs20244 小时前
Swift 类型转换
开发语言
前端小L5 小时前
贪心算法专题(十):维度权衡的艺术——「根据身高重建队列」
javascript·算法·贪心算法
秃了也弱了。5 小时前
python实现定时任务:schedule库、APScheduler库
开发语言·python
weixin_440730505 小时前
java数组整理笔记
java·开发语言·笔记
Thera7775 小时前
状态机(State Machine)详解:原理、优缺点与 C++ 实战示例
开发语言·c++
niucloud-admin6 小时前
java服务端——controller控制器
java·开发语言
Fortunate Chen6 小时前
类与对象(下)
java·javascript·jvm