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();
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
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
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With