【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
  },
}
相关推荐
循环过三天3 分钟前
3.4、Python-集合
开发语言·笔记·python·学习·算法
_院长大人_2 小时前
设计模式-工厂模式
java·开发语言·设计模式
MATLAB代码顾问2 小时前
MATLAB实现决策树数值预测
开发语言·决策树·matlab
devincob3 小时前
js原生、vue导出、react导出、axios ( post请求方式)跨平台导出下载四种方式的demo
javascript·vue.js·react.js
编程社区管理员3 小时前
React 发送短信验证码和验证码校验功能组件
前端·javascript·react.js
葡萄城技术团队3 小时前
迎接下一代 React 框架:Next.js 16 核心能力解读
javascript·spring·react.js
全马必破三3 小时前
React“组件即函数”
前端·javascript·react.js
不染尘.3 小时前
2025_11_7_刷题
开发语言·c++·vscode·算法
課代表3 小时前
JavaScript 中获取二维数组最大值
javascript·max·数组·递归·array·最大值·二维
似水এ᭄往昔3 小时前
【C++】--stack和queue
开发语言·c++