另一种关于类的小例

前言

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

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);

在这里插入图片描述

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

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);

在这里插入图片描述

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

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);

在这里插入图片描述

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

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);

在这里插入图片描述

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

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

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值