Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set up individual private variables when using Object.create

Tags:

javascript

oop

I have a prototype function which I use to make two other functions with Object.create(). The private variables, however, are shared. How can I make each instance have its own instance of the variables?

var testCodePrototype = (function(){
  var score = 0;
  this.updateScore= function(amount){
    score += amount;
    return "Score updated to " + score;
  };
  this.getScore = function(){
    return score;
  };
  return {
    updateScore,
    getScore,
  };
}());
      
var test1 = Object.create(testCodePrototype, {
  name: {value: function(type){
  	return "I am test1";
  }}
});
var test2 = Object.create(testCodePrototype, {
  name: {value: function(type){
  	return "I am second.";
  }}
});

console.log(test1.name());
console.log(test2.name());
console.log(test1.updateScore(5));
console.log(test1.getScore()); // returns 5
console.log(test2.getScore()); // returns 5!!
like image 897
brentonstrine Avatar asked Dec 21 '25 17:12

brentonstrine


1 Answers

You should create a property score inside each object and use it with this qualifier:

var testCodePrototype = (function(){

    this.updateScore= function(amount){
        this.score += amount;
        return "Score updated to " + this.score;
    };
    this.getScore = function(){
        return this.score;
    };
    return {
        updateScore,
        getScore
    };
}());

var test1 = Object.create(testCodePrototype, {
    name: {value: function(type){
        return "I am test1";
    }},
    score: {writable:true,value:0}
});

var test2 = Object.create(testCodePrototype, {
    name: {value: function(type){
        return "I am second";
    }},
    score: {writable:true,value:0}
});

console.log(test1.name());
console.log(test2.name());
console.log(test1.updateScore(5));
console.log(test1.getScore());  // 5
console.log(test2.getScore());  // 0
like image 157
Thevs Avatar answered Dec 23 '25 05:12

Thevs