【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
  },
}
相关推荐
共享家952736 分钟前
Qt 实战-Music 播放器
开发语言·qt
上不如老下不如小39 分钟前
2025年第七届全国高校计算机能力挑战赛 决赛 Python组 编程题汇总
开发语言·python
老华带你飞40 分钟前
校园快递|基于Java校园快递管理系统(源码+数据库+文档)
java·开发语言·数据库·vue.js·spring boot
smile_Iris2 小时前
Day 32 类的定义和方法
开发语言·python
AndreasEmil2 小时前
JavaSE - 继承
java·开发语言·ide·vscode·intellij-idea·idea
苏打水com8 小时前
第九篇:Day25-27 Vue进阶——组件复用与状态管理(对标职场“复杂项目”需求)
前端·javascript·vue.js
老华带你飞8 小时前
博物馆展览门户|基于Java博物馆展览门户系统(源码+数据库+文档)
java·开发语言·数据库·vue.js·spring boot·后端
liulilittle8 小时前
FileStream C++
开发语言·c++·cocoa
点PY8 小时前
C++ 中 std::async 和 std::future 的并发性
java·开发语言·c++
不会代码的小猴8 小时前
C++的第九天笔记
开发语言·c++·笔记