【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
  },
}
相关推荐
Risehuxyc19 分钟前
来自PHP项目devnexen的回信
开发语言·php
FRing0339 分钟前
vue2干货总结10(json-server、vant-ui、postcss插件、axios二次封装、图形验证码、toast轻提示)
开发语言·前端·vue.js·ui·json·vue2·postcss
程序员大阳43 分钟前
副队长ES6+教程(5)--模板字符串
javascript·vue.js·es6·模板字符串
我是大猴子1 小时前
分析sss
开发语言
安若浮生1 小时前
从零写一个 HarmonyOS NEXT 影视聚合播放器,我踩过的 14 个坑
javascript
geats人山人海1 小时前
现代c++4.1
java·开发语言·c++
程序员大阳1 小时前
副队长ES6+教程(4)--拓展运算符
javascript·vue.js·es6·收集·拓展运算符·展开
布莱克6052 小时前
Swift 字符串详解:从基础用法到性能与最佳实践
服务器·开发语言·ssh·字符串·swift
Mh2 小时前
AI 的模型能力越来越强,为什么我的编码能力越来越弱?
前端·javascript·后端
饿了吃洗衣凝珠3 小时前
SELinux
服务器·开发语言·php