【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
  },
}
相关推荐
一只鹿鹿鹿17 小时前
信息化项目管理规范(参考Word文件)
java·大数据·运维·开发语言·数据库
XGeFei17 小时前
python中子线程与主线程的关系
开发语言·python
kyriewen17 小时前
面试8家前端岗位后,我发现了一个残酷的事实:AI不是加分项,是门槛
前端·javascript·面试
Chase_______17 小时前
【Java杂项】final 关键字详解:变量、方法、类限制与引用可变性
java·开发语言·python
ruxingli17 小时前
Golang iota详解
开发语言·后端·golang
我材不敲代码17 小时前
Python venv 虚拟环境从入门到精通 + uv 高性能替代工具实战指南
开发语言·python·uv
l1t17 小时前
DeepSeek总结的使用实体-组件-系统和基于存在性处理进行Python编程18-20
开发语言·python
磊 子17 小时前
STL之deque和list以及两者与vector的对比
开发语言·c++·list
凤山老林17 小时前
DDD(领域驱动设计)在复杂业务系统中的落地指南
java·开发语言·数据库·ddd·领域驱动
凯瑟琳.奥古斯特18 小时前
子查询原理与实战案例解析
开发语言·数据库·职场和发展·数据库开发