另一种关于类的小例

前言

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

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

相关推荐
tiandyoin17 分钟前
Notepad++ 修改 About
前端·notepad++·html5
深圳智物通讯32 分钟前
安卓开发板_联发科MTK开发板使用ADB开发
android·adb·安卓开发板
职场人参43 分钟前
怎么将几个pdf合成为一个?把几个PDF合并成为一个的8种方法
前端
居安思危_Ho1 小时前
【Android笔记】Android Studio打包 提示Invalid keystore format
android·笔记·gradle·android studio·android 打包
二豆是富婆1 小时前
vue3 element plus table 滚动到指定位置
javascript·vue.js·elementui
学前端搞口饭吃2 小时前
vue2-ssr从vue-cli搭建项目改造服务端渲染+打包上线部署
前端·javascript·vue.js
鱼在在2 小时前
uni-app 聊天界面滚动到消息底部
javascript·uni-app·vue
CRMEB系统商城2 小时前
前端项目node版本问题导致依赖安装异常的处理办法
前端
anyup_前端梦工厂2 小时前
Vue 中常用的基础指令
前端·javascript·vue.js
coderYYY2 小时前
CSS实现原生table可拖拽调整列宽
前端·css·html·css3