【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 分钟前
C++类和对象(中)
开发语言·c++
kgduu32 分钟前
js之表单
开发语言·前端·javascript
钊兵34 分钟前
java实现GeoJSON地理信息对经纬度点的匹配
java·开发语言
毕设源码-钟学长42 分钟前
【开题答辩全过程】以 基于Python的健康食谱规划系统的设计与实现为例,包含答辩的问题和答案
开发语言·python
秋刀鱼程序编程42 分钟前
Java基础入门(五)----面向对象(上)
java·开发语言
Remember_9931 小时前
【LeetCode精选算法】滑动窗口专题二
java·开发语言·数据结构·算法·leetcode
Filotimo_1 小时前
在java开发中,cron表达式概念
java·开发语言·数据库
码农水水2 小时前
京东Java面试被问:HTTP/2的多路复用和头部压缩实现
java·开发语言·分布式·http·面试·php·wpf
摘星编程2 小时前
React Native for OpenHarmony 实战:Picker 选择器组件详解
javascript·react native·react.js
你怎么知道我是队长2 小时前
C语言---未定义行为
java·c语言·开发语言