另一种关于类的小例

前言

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

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他才有效,所以在开发中,数据封装和数据隐私非常非常重要,后面的话我们的文章再分享学习

相关推荐
鱼樱前端18 分钟前
今天介绍下最新更新的Vite7
前端·vue.js
coder_pig1 小时前
跟🤡杰哥一起学Flutter (三十四、玩转Flutter手势✋)
前端·flutter·harmonyos
万少1 小时前
01-自然壁纸实战教程-免费开放啦
前端
独立开阀者_FwtCoder1 小时前
【Augment】 Augment技巧之 Rewrite Prompt(重写提示) 有神奇的魔法
前端·javascript·github
yuki_uix1 小时前
AI辅助网页设计:从图片到代码的实践探索
前端
我想说一句1 小时前
事件机制与委托:从冒泡捕获到高效编程的奇妙之旅
前端·javascript
陈随易1 小时前
MoonBit助力前端开发,加密&性能两不误,斐波那契测试提高3-4倍
前端·后端·程序员
汤姆Tom1 小时前
JavaScript reduce()函数详解
javascript
小飞悟1 小时前
你以为 React 的事件很简单?错了,它暗藏玄机!
前端·javascript·面试
中微子2 小时前
JavaScript 事件机制:捕获、冒泡与事件委托详解
前端·javascript