【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
  },
}
相关推荐
岁岁养乐多14 分钟前
Java 序列化相关问题
java·开发语言
CAE二次开发工程师21 分钟前
【C语言入门到精通】-基础篇
c语言·开发语言·python
AAIshangyanxiu1 小时前
涡度通量碳观测数据 MATLAB 全流程解析与敏感性定量分析、观测数据质控、插补及 footprint 建模技术
开发语言·matlab·涡度通量·生态碳汇·生态碳汇模拟
小短腿乄1 小时前
java实现pdf加水印+签名
java·开发语言·pdf
聆风吟º1 小时前
【金仓数据库征文】Java 应用接入金仓数据库:从驱动、连接池到存储过程调试的踩坑实录
java·开发语言·数据库
不会代码的小猴2 小时前
11. 类和动态内存分配
开发语言·c++
似璟如你3 小时前
Java 开发者的 Go 语法基础:从 0 开始快速上手 Go
java·开发语言·后端·golang·go·编程语言
LccKyI3 小时前
C#学习day05(开发福彩双色球系统附思维导图)
开发语言·学习·c#
zzz_23683 小时前
TencentDB-Agent-Memory 深度解析:让多个 Agent 共享项目经验的记忆中枢
java·开发语言·jvm·人工智能·agent·memory·tencent db
vx-程序开发3 小时前
django医院预约挂号系统---附源码23353
java·javascript·spring boot·python·eclipse·django·php