Nizar AYARI
Nizar AYARI

Reputation: 203

javascript prototype and private variable

  1. How can I make my min function working. I got banque is undefined?

Thanks.

  1. List item
  2. List item
  3. List item

function Personne(nom){
  this.nom = nom;
  var banque = 1500;
  this.add = function(number){
    banque = banque + number
  }
  this.getCpte = function() {
    return banque
  }
}

Personne.prototype.min = function(number){
  banque = banque - number
}

var me = new Personne('albert')



console.log(me)
me.add(500)
me.min(500) // got banque is undefined
console.log(me.getCpte())

Upvotes: 1

Views: 40

Answers (2)

Bergi
Bergi

Reputation: 664297

banque is a local variable inside Personne, and you cannot access it from outside. Either put min inside the constructor to make it a privileged method like the others, or make banque a property like .nom.

Or just do everything through the add method:

Personne.prototype.min = function(number) {
    this.add(-number);
};

Upvotes: 1

Andrew Li
Andrew Li

Reputation: 57934

What you can do is set up a getter for banque so you can use the prototype. It seems like you've already done this with getCpte. Just use that function to get the value of banque and use that in the prototype function assignment. You will also need a setter for banque if you want to modify the value outside the Personne function (this will make banque essentially public. To combat this, set the min function in the constructor if at all possible):

function Personne(nom){
  this.nom = nom;
  var banque = 1500;
  this.add = function(number){
    banque = banque + number
  }
  this.getCpte = function() { //banque getter
    return banque
  }
  this.setCpte = function(value) { //banque setter
    banque = value;
  }  
}

Personne.prototype.min = function(number){
  this.setCpte(this.getCpte() - number) //set to banque - number
}

var me = new Personne('albert')

console.log(me)
me.add(500)
me.min(500)
console.log(me.getCpte())

What this adds is a function setCpte which is a setter for banque. This way, we can use this.setCpte(value) where value is the value being set to banque. Since you did banque - number, we can use the getter to get rid of the ReferenceError, and subtract number from it.

Upvotes: 0

Related Questions