【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
  },
}
相关推荐
geovindu6 分钟前
rust: Timing Functions Pattern
开发语言·后端·设计模式·rust·计时函数模式·性能分析型模式
geovindu44 分钟前
python:Lasso
开发语言·后端·python·算法
多加点辣也没关系1 小时前
JavaScript|第42章:安全与最佳实践
开发语言·javascript·安全
3095566661 小时前
股票数据落库前的去重与主键设计:一次 SQLite 写入实录
java·开发语言·jvm·数据库·redis·python·sqlite
泯泷1 小时前
第三章:lit-html的威力 - 精通声明式模板
前端·javascript·web components
利威尔xu2 小时前
2026-11-19-Go反射为什么慢面试
开发语言·面试·golang
bai2732 小时前
npm 在 cmd 里能跑,Node 的 spawn 一调就 EINVAL:Windows 上 .cmd 的六种调法实测
javascript·后端
山楂树の3 小时前
Python 函数:参数、作用域、Lambda 与类型注解
开发语言·python
旖旎夜光3 小时前
【C 语言】(一)(下)指针进阶:const、二级指针、函数指针与指针题
c语言·开发语言·笔记·学习
炸薯条!3 小时前
Python装饰器详解:从闭包原理到语法糖,再到多个装饰器
开发语言·python