另一种关于类的小例

前言

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

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

相关推荐
不爱吃饭爱吃菜31 分钟前
uniapp微信小程序-长按按钮百度语音识别回显文字
前端·javascript·vue.js·百度·微信小程序·uni-app·语音识别
dancing9991 小时前
Android Studio中Gradle 7.0上下项目配置及镜像修改
android·ide·android studio
程序员拂雨1 小时前
Angular 知识框架
前端·javascript·angular.js
GoodStudyAndDayDayUp2 小时前
gitlab+portainer 实现Ruoyi Vue前端CI/CD
前端·vue.js·gitlab
程序员阿明2 小时前
vite运行只能访问localhost解决办法
前端·vue
前端 贾公子2 小时前
uniapp -- 验证码倒计时按钮组件
前端·vue.js·uni-app
zhengddzz2 小时前
从卡顿到丝滑:JavaScript性能优化实战秘籍
开发语言·javascript·性能优化
淡笑沐白2 小时前
AJAX技术全解析:从基础到最佳实践
前端·ajax
Go_going_2 小时前
ajax,Promise 和 fetch
javascript·ajax·okhttp
EQ-雪梨蛋花汤2 小时前
【Part 2安卓原生360°VR播放器开发实战】第四节|安卓VR播放器性能优化与设备适配
android·性能优化·vr