【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
  },
}
相关推荐
方华世界26 分钟前
企业级Java AI Agent应用平台
java·开发语言·人工智能
ujainu小1 小时前
原生性能优化:6变量实现高效桥接
开发语言·华为·性能优化·harmonyos
李明卫杭州1 小时前
Vue2 portal-target 组件与 Vue3 的针对性优化
前端·javascript·vue.js
甄同学1 小时前
第十七篇:Bash Executor命令执行器,安全运行Shell命令
开发语言·安全·bash
张3231 小时前
Go语言基础 Map 函数值 闭包
开发语言·golang
杜子不疼.1 小时前
【C++ 在线五子棋对战】- 会话管理模块实现
开发语言·c++
有点。1 小时前
C++深度优先搜索(DFS)的概念(一)
开发语言·c++·深度优先
时间的拾荒人2 小时前
C语言编译与链接:从源码到可执行程序的完整解析
c语言·开发语言
人道领域2 小时前
【0-1的agent进阶篇】Prompt 与上下文工程
java·开发语言·prompt·mcp
aaPIXa6222 小时前
C++大型项目模块化拆分实战记录
开发语言·c++