如何将参数传递给自治函数并获取值?

How to pass the parameter to autonomous function and get the values?

加载文档时,我正在启动一个调用自身的函数。后来从返回的函数中,我试图获得输出。但我没有得到。我在这里做错的方式。

谁能指正一下自启动功能的正确使用方法?

这是我的尝试:

var BankAccount = (function () { 

  function BankAccount() { 
    this.balance = 0; 
  } 

  BankAccount.prototype.deposit = function(credit) { 
    this.balance += credit; return this.balance; 
  }; 

  return BankAccount; 

})();

var myDeposit = BankAccount.deposit(50); //throws error as ankAccount.deposit is not a function

Live

您需要先调用构造函数才能调用 .deposit

var account = new BankAccount();
var balance = account.deposit(50);
console.log(balance); // 50

这将允许您管理多个帐户,每个帐户都有自己的余额。

var a = new BankAccount();
a.deposit(50); // 50

var b = new BankAccount();
b.deposit(20); // 20

console.log(a.balance); // 50
console.log(b.balance); // 20

您需要 return BankAccount 实例:

return new BankAccount();

你已经写了一个构造函数,但是你还没有调用它。

var myBankAccount = new BankAccount();
var myDeposit = myBankAccount.deposit(50);