【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
  },
}
相关推荐
空&白5 小时前
vue暗黑模式
javascript·vue.js
执风挽^5 小时前
Python基础编程题2
开发语言·python·算法·visual studio code
Z9fish6 小时前
sse哈工大C语言编程练习20
c语言·开发语言·算法
VT.馒头6 小时前
【力扣】2695. 包装数组
前端·javascript·算法·leetcode·职场和发展·typescript
萧鼎6 小时前
Python 包管理的“超音速”革命:全面上手 uv 工具链
开发语言·python·uv
css趣多多6 小时前
一个UI内置组件el-scrollbar
前端·javascript·vue.js
-凌凌漆-6 小时前
【vue】pinia中的值使用 v-model绑定出现[object Object]
javascript·vue.js·ecmascript
Anastasiozzzz6 小时前
Java Lambda 揭秘:从匿名内部类到底层原理的深度解析
java·开发语言
刘琦沛在进步6 小时前
【C / C++】引用和函数重载的介绍
c语言·开发语言·c++
机器视觉的发动机7 小时前
AI算力中心的能耗挑战与未来破局之路
开发语言·人工智能·自动化·视觉检测·机器视觉