【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
  },
}
相关推荐
脚踏实地皮皮晨24 分钟前
003003001_Grid控件
开发语言·windows·算法·c#·visual studio
十年磨剑走天涯28 分钟前
C++ STL 容器操作复杂度速查表
开发语言·c++
万少30 分钟前
DeepSeek-V4-Flash 正式版上线了,但这 3 个坑我帮你提前踩了
前端·javascript·后端
always_TT35 分钟前
【Python requirements.txt 依赖管理】
开发语言·python
15Moonlight44 分钟前
C++进阶(09):特殊类设计
开发语言·c++
宁风NF1 小时前
JavaScript:网络请求与前端通信
开发语言·前端·javascript·网络·学习·ecmascript
Logintern091 小时前
py文件开头为什么需要加:from __future__ import annotations
开发语言·python
猫猫不是喵喵.1 小时前
Vue3 中 computed 计算属性与 watch、watchEffect 监听
前端·javascript·vue.js
techdashen1 小时前
Go设计取舍之三: 0.3ns每次的错误Benchmark
开发语言·后端·golang