简体   繁体   English

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

[英]How to pass the parameter to autonomous function and get the values?

On load of the document, I am initiating a function calling itself. 在加载文档时,我正在启动一个调用自身的函数。 And later from the returned function, i am trying to get the output. 后来从返回的函数中,我试图获取输出。 but i am not getting. 但是我没有。 the way what i do this wrong here. 我在这里做错了的方式。

any one correct me and teach the correct way to use the self initiated functions? 任何人都可以纠正我并教导使用自动启动功能的正确方法吗?

here is my try : 这是我的尝试:

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 生活

You need to invoke your constructor before you can call .deposit 您需要先调用构造函数,然后才能调用.deposit

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

This would allow you to manage multiple accounts where each account has its own balance. 这将允许您管理多个帐户,每个帐户都有自己的余额。

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

您需要返回BankAccount的实例:

return new BankAccount();

You've written a constructor function, but you haven't called it as one. 您已经编写了一个构造函数,但尚未将其称为一个。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM