【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
  },
}
相关推荐
晨曦夜月7 分钟前
笔试强训day7
开发语言·c++·算法
Kurbaneli10 分钟前
先啃C语言还是直奔目标?
开发语言
weixin_3077791328 分钟前
Jenkins Pipeline 完全指南:核心概念、使用详解与最佳实践
开发语言·ci/cd·自动化·jenkins·etl
kk”31 分钟前
c++红黑树
开发语言·c++
Gomiko32 分钟前
JavaScript DOM 原生部分(二):元素内容修改
开发语言·javascript·ecmascript
一招定胜负34 分钟前
网络爬虫(第三部)
前端·javascript·爬虫
Z_W_H_35 分钟前
【C#】C#中值类型和引用类型参数传递的区别
开发语言·c#
Data_agent41 分钟前
实战:用Splash搞定JavaScript密集型网页渲染
开发语言·javascript·ecmascript
leiming643 分钟前
C++ 02 函数模板案例
开发语言·c++·算法
weixin_4215850144 分钟前
PYTHON 迭代器1 - PEP-255
开发语言·python