Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shared array between class instances in node.js

I have a a weird problem in node.js:

person.js

var Person;

Person = (function() {
  Person.prototype.name = "";
  Person.prototype.friends = [];

  function Person(name) {
    if (name) {
      this.name = name;
    }
  }

  Person.prototype.sayHello = function() {
    return console.log("Hello, my name is " + this.name + " and I have " + this.friends.length + " friends");
  };

  Person.prototype.addFriend = function(name) {
    this.friends.push(name);
  };

  return Person;

})();

module.exports = Person; 

factory.js

var Person = require('./Person.js');

module.exports = function(name) {
  return new Person(name);
};

index.js

factory = require('./factory');

tyrion = factory("Tyrion");
tyrion.addFriend("Bronn");
tyrion.sayHello();
daenerys = factory("Daenerys");
daenerys.addFriend("Illyrio");
daenerys.addFriend("Daario");
daenerys.addFriend("Barristan");
daenerys.sayHello();
tyrion.sayHello();

Actual output

Hello, my name is Tyrion and I have 1 friends
Hello, my name is Daenerys and I have 4 friends
Hello, my name is Tyrion and I have 4 friends

Expected output

Hello, my name is Tyrion and I have 1 friends
Hello, my name is Daenerys and I have 3 friends
Hello, my name is Tyrion and I have 1 friends

How come that adding element to one instance does add it for both? It looks like the friend array is "shared" between instances. How to prevent such?

Demo here

like image 262
Vinz243 Avatar asked Feb 13 '23 01:02

Vinz243


1 Answers

Remove lines

Person.prototype.name = "";
Person.prototype.friends = [];

add them to constructor instead:

this.name = name;
this.friends = [];

At the moment all prototypes share same object friends.

like image 61
Anatoliy Avatar answered Feb 14 '23 18:02

Anatoliy