【问题标题】:creating a basic bank system, keyword 'this' in javascript在javascript中创建一个基本的银行系统,关键字'this'
【发布时间】:2016-12-05 02:11:13
【问题描述】:

我的任务是创建一个包含多个帐户的银行。银行需要一种方法来返回账户中的总金额。它还需要一个 addAccount 方法,该方法将在银行注册一个新帐户并将其添加到帐户数组中。您应该能够从帐户中存款或取款以更改余额。确保帐户不能有负值。在银行上写一个“转账”,允许您在两个账户之间转账。

我的问题是想办法打印出每个用户的详细信息(姓名、余额)。我觉得通过应用关键字this,我错过了某种链接。 这是我的代码:

var account = function (name, balance){

  account.name = name;
  account.balance = balance;

  account.deposit = function (depositAmount) {
    newBalance = account.balance - depositAmount;
    console.log("Your balance is now " + newBalance);
    if (newBalance <= 0) {
      console.log("You have insufficient funds!!!");
    }
  };

  account.withdraw = function (withdrawAmount){
    newBalance = account.balance - withdrawAmount;
    console.log("Your balance is now " + newBalance);
    if (newBalance <= 0) {
      console.log("You have insufficient funds!!!");
    }

  };

  account.transfer = function (transferAmount){
//got stuck here
  }

  console.log("Name: " + name + "; Balance: " + balance);
}


var AustinAccount = new account ("Austin", 500);
var KateAccount = new account ("Kate", 10000);
var GingerAccount = new account ("Ginger", 70000000);
var OreoAccount = new account ("Oreo", 900000000);

【问题讨论】:

  • 你有什么问题?
  • 代码有效吗?你有什么错误吗?
  • 是的,我发现所有答案都非常有帮助。我想我很难理解如何使用这个关键词。我还在学习这是我做 javascript 的第一周。谢谢大家!

标签: javascript this


【解决方案1】:

提示和技巧

让我们从基础开始:

构造函数应该以大写字母开头:

function Account(name, balance) {

}

然后,正如@Ibar 所说,您应该使用this 来引用构造函数实例,而不是通过名称调用它。

function Account(name, balance) {
  this.name = name;
  ...
}

然后,您可以通过以下方式访问任何实例属性:

var account = new Account('Hey', 100);
console.log(account.name);

另外,定义构造方法的正确方法是:

function Account(name, balance) {

}

Account.prototype.deposit = function(arg) {

}

工作脚本

在这里您可以找到一个工作脚本,我添加了两个私有方法(_isPositive_isAllowed)检查给定金额是否为正数,以及在给定交易后帐户中是否有足够的资金。

function Account(name, balance) {
  this.name = name;
  this.balance = balance;
}

Account.prototype.deposit = function(amount) {
  if (this._isPositive(amount)) {
    this.balance += amount;
    console.info(`Deposit: ${this.name} new balance is ${this.balance}`);
    return true;
  }
  return false;
}

Account.prototype.withdraw = function(amount) {
  if (this._isAllowed(amount)) {
    this.balance -= amount;
    console.info(`Withdraw: ${this.name} new balance is ${this.balance}`);
    return true;
  }
  return false;
}

Account.prototype.transfer = function(amount, account) {
  if (this.withdraw(amount) && account.deposit(amount)) {
    console.info(`Transfer: ${amount} has been moved from ${this.name} to ${account.name}`);
    return true;
  }
  return false;
}


Account.prototype._isPositive = function(amount) {
  const isPositive = amount > 0;
  if (!isPositive) {
    console.error('Amount must be positive!');
    return false;
  }
  return true;
}

Account.prototype._isAllowed = function(amount) {
  if (!this._isPositive(amount)) return false;

  const isAllowed = this.balance - amount >= 0;
  if (!isAllowed) {
    console.error('You have insufficent funds!');
    return false;
  }
  return true;
}

const a = new Account('a', 100);
const b = new Account('b', 0);


output.innerText += `before:  a: ${a.balance}, b: ${b.balance}\n`;

a.transfer(100, b);

output.innerText += `after:  a: ${a.balance}, b: ${b.balance}\n`;
&lt;div id=output&gt;&lt;/div&gt;

改进

然后您可以进一步改进您的脚本,添加交易日志,甚至可能是管理不同银行的方法

const fooBank = new Bank('foo');
const fezAccount = new fooBank.Account('fez', 0);

希望对你有帮助。

【讨论】:

  • 这很有帮助,谢谢!您介意解释一下什么是原型以及为什么在这种情况下使用它吗?
  • 我还注意到,您没有使用“var”,而是使用了“const”。有什么不同吗?
  • const是JS的一个新特性,它允许定义一旦定义就不能编辑的常量。关于prototype,请阅读developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…。请记住将答案标记为正确。
  • 关于标记答案,因为我很新……你只能标记一个答案正确吗?每个正确的答案我都去标记了,之前的绿色勾号好像变回了灰色。
  • 是的,您只能将其中一项标记为正确(最好的一项),您仍然可以为您喜欢的人打分(使用向上箭头)
【解决方案2】:

account 函数中,您应该将account 替换为this

var account = function (name, balance){
     this.name = name; 
     this.balance = balance; 

     this.deposit = function (depositAmount) {
         ...
     }
}

创建account 对象后,您可以调用AustinAccount.balance 来检索有关您的对象的信息。

【讨论】:

    【解决方案3】:

    查看这个 JSBin:http://jsbin.com/jiheqotaye/edit?js,console

    Fez 所说的一切正是您在编写易于理解的构造函数时需要考虑的内容。

    使用transfer 方法;您想检查传入的 account 是否是同一构造函数的实例。然后检查withdraw是否成功,然后进行存款。

    Account.prototype.transfer = function (transferAmount, account){
      if (account instanceof Account) {
        if (this.withdraw(transferAmount)) {
          account.deposit(transferAmount);
          return true;
        } else {
          console.log("An error occured withdrawing that amount");
          return false;
        }
      }
      console.log("Provided account was not an account with our bank");
      return false;
    };
    

    希望有帮助!

    【讨论】:

    • 为什么要查看instanceof?如果两家银行共享一个兼容的 API,您不应阻止转账:P
    • instanceof是严格保证API兼容性的简化版。我不希望我的钱意外地落入任何旧对象;)
    • 我明白了,是的,最好小心自己的钱。
    猜你喜欢
    • 2010-10-07
    • 2018-01-07
    • 2013-07-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多