另一种关于类的小例

前言

我们还是以一段关于构造函数的代码作为开端,我们以之前银行家的小项目为背景

javascript 复制代码
class Account {
  constructor(owner, currency, pin) {
    this.owner = owner;
    this.currency = currency;
    this.pin = pin;
  }
}

const ITshare = new Account('ITshare', 'EUR', '21211');
console.log(ITshare);

● 我们可以设置一个欢迎语

javascript 复制代码
class Account {
  constructor(owner, currency, pin) {
    this.owner = owner;
    this.currency = currency;
    this.pin = pin;
    this.locale = navigator.language;

    console.log(`欢迎来到你的账户,${owner}`);
  }
}

const ITshare = new Account('ITshare', 'EUR', '21211');
console.log(ITshare);

● 但是如果现在我们需要一个存钱和取钱的数组,用于记录,该怎么去做呢?当然我们可以用传统的方法

javascript 复制代码
class Account {
  constructor(owner, currency, pin) {
    this.owner = owner;
    this.currency = currency;
    this.pin = pin;
    this.movements = [];
    this.locale = navigator.language;

    console.log(`欢迎来到你的账户,${owner}`);
  }
}

const ITshare = new Account('ITshare', 'EUR', '21211');
ITshare.movements.push(250);
ITshare.movements.push(-156);
console.log(ITshare);

● 上面未必显得有点不高级了,可以像下面这样的写

javascript 复制代码
class Account {
  constructor(owner, currency, pin) {
    this.owner = owner;
    this.currency = currency;
    this.pin = pin;
    this.movements = [];
    this.locale = navigator.language;

    console.log(`欢迎来到你的账户,${owner}`);
  }

  deposit(val) {
    this.movements.push(val);
  }

  withraw(val) {
    this.deposit(-val);
  }
}

const ITshare = new Account('ITshare', 'EUR', '21211');
ITshare.deposit(250);
ITshare.withraw(120);
console.log(ITshare);

上面的取钱和存钱的操作就属于公共接口,所有人在存钱或者取钱的时候都是调用同样的方法;

● 我们可以像之前那样实现一个贷款的样例

javascript 复制代码
class Account {
  constructor(owner, currency, pin) {
    this.owner = owner;
    this.currency = currency;
    this.pin = pin;
    this.movements = [];
    this.locale = navigator.language;

    console.log(`欢迎来到你的账户,${owner}`);
  }

  deposit(val) {
    this.movements.push(val);
  }

  withraw(val) {
    this.deposit(-val);
  }

  approveLoan(val) {
    return true;
  }

  requestLoan(val) {
    if (this.approveLoan(val)) {
      this.deposit(val);
      console.log('恭喜你!贷款成功');
    }
  }
}

const ITshare = new Account('ITshare', 'EUR', '21211');
ITshare.deposit(250);
ITshare.withraw(120);
ITshare.requestLoan(1000);
console.log(ITshare);

上面的方法中,approveLoan方法只有被requestLoan他才有效,所以在开发中,数据封装和数据隐私非常非常重要,后面的话我们的文章再分享学习

相关推荐
EndingCoder几秒前
图算法在前端的复杂交互
前端·算法·图算法
Attacking-Coder4 分钟前
前端面试宝典---项目难点2-智能问答对话框采用虚拟列表动态渲染可视区域元素(10万+条数据)
开发语言·前端·javascript
kirinlau8 分钟前
JavaScript中Object.defineProperty的作用和用法以及和proxy的区别
javascript·ecmascript
Risehuxyc10 分钟前
前端同学,你能不能别再往后端传一个巨大的JSON了?
前端·json·状态模式
Adolf_199318 分钟前
axios拦截器
前端·javascript
一一一87129 分钟前
JavaScript 中的 this:谁在调用我?
javascript
多啦C梦a29 分钟前
《ProtectRoute怎么用?》 前端登录拦截器!React ProtectRoute + 懒加载,从入门到会用
前端·javascript·react.js
AliciaIr31 分钟前
JavaScript事件循环机制:从底层原理到幽默解读
javascript
sophie旭31 分钟前
《深入浅出react》总结之 10.3 Commit阶段流程探秘
前端·react.js·源码阅读
绅士玖32 分钟前
🔍 深入理解React的useContext Hook:从原理到实战
前端·react.js