【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
  },
}
相关推荐
灵感__idea3 小时前
Hello 算法:“走一步看一步”的智慧
前端·javascript·算法
清水白石0084 小时前
Python 编程实战全景:从基础语法到插件架构、异步性能与工程最佳实践
开发语言·python·架构
Mh5 小时前
我决定写一个 3D 地球仪来记录下我要去的地方
前端·javascript·动效
. . . . .6 小时前
ref、useRef 和 forwardRef
前端·javascript·react.js
Halo_tjn6 小时前
Java 基于字符串相关知识点
java·开发语言·算法
梦想的颜色7 小时前
java 利用redis来限制用户频繁点击
java·开发语言
报错小能手7 小时前
Swift 并发 Combine响应式框架
开发语言·ios·swift
柚子8167 小时前
break跳出语句块的神奇技巧
前端·javascript
万法若空7 小时前
C++ <memory> 库全方位详解
开发语言·c++
代码中介商7 小时前
C++ 类型转换深度解析:static_cast、dynamic_cast、const_cast、reinterpret_cast
开发语言·c++