【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
  },
}
相关推荐
草莓橙子碗31 分钟前
Claude 使用指南
开发语言·python
longxiaozhang61 小时前
C# Array类:数组其实没那么难
开发语言·c#
互联网中的一颗神经元2 小时前
06. Small 对象分配:mcache 无锁路径
开发语言·golang
日光倾2 小时前
TypeScript 随手记 —— 1
前端·javascript·typescript
PPPPickup2 小时前
金证秋招笔试
java·开发语言
不正经学生2 小时前
C语言结构体:自定义数据类型,让变量打包出行
java·c语言·开发语言·数据结构·算法
老一岁2 小时前
c问题总结(1)
c语言·开发语言
林森lsjs3 小时前
队列 FIFO 原理 & 手撕两种队列实现(链表 + 循环数组)—数据结构陆
java·开发语言·数据结构·队列
何以解忧,唯有..4 小时前
Python time 模块详解:时间处理与日期操作指南
开发语言·python
caimouse4 小时前
ReactOS 窗口系统分析(20):光标与图标 — cursoricon.c
c语言·开发语言