【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
  },
}
相关推荐
不会写代码的ys3 分钟前
C++复习篇
java·开发语言·c++
雨师@7 分钟前
go语言项目--实例化(图书管理)--005
开发语言·后端·golang
Aspiresky18 分钟前
探索Rust语言之引用
开发语言·后端·rust
天空'之城22 分钟前
Linux 系统编程 10:线程同步
linux·开发语言·系统编程·线程同步
Vect__25 分钟前
Go 数据结构 slice 深度剖析
开发语言·数据结构·golang
想你依然心痛26 分钟前
AtomCode在Python数据科学项目中的使用体验:从数据分析到可视化
开发语言·python·数据分析
满天星830357729 分钟前
【Qt】控件(二) (geometry及与frameGeometry的区别)
开发语言·qt
wabil33 分钟前
【LVGL】滑动切换页面的界面优化实践
开发语言·ios·swift
Esaka_Forever1 小时前
Python 与 JS (V8) 垃圾回收核心区别 + 底层根源分析
开发语言·javascript·jvm
林希_Rachel_傻希希1 小时前
web性能优化之——AI总结视频
前端·javascript·面试