Why Returns Nan? and how to return Number?

Asked

Viewed 107 times

1

Why does the following code return Nan (Not a Number)? - and how to return the result of (balance) * (index) in number?

function ContaPoupanca(){
            this.saldo = 0;
            this.deposita = function(valor){
                this.saldo += valor;
            };
            this.atualiza = function(indice){
                this.saldo += this.saldo * this.indice;
            };
        };
var contaPoupanca = new ContaPoupanca();
contaPoupanca.deposita(1000);
console.log(contaPoupanca.saldo);
contaPoupanca.atualiza(0.05);
console.log(contaPoupanca.saldo);

  • Switch from this.Indice to Indice

1 answer

5


The mistake is in this.indice. You are trying to access a property of your object ContaPoupanca which does not exist, instead of accessing the function parameter. The correct one is only indice. Behold:

function ContaPoupanca(){
            this.saldo = 0;
            this.deposita = function(valor){
                this.saldo += valor;
            };
            this.atualiza = function(indice){
                this.saldo += this.saldo * indice;
            };
        };
var contaPoupanca = new ContaPoupanca();
contaPoupanca.deposita(1000);
console.log(contaPoupanca.saldo);
contaPoupanca.atualiza(0.05);
console.log(contaPoupanca.saldo);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.