gpt4 book ai didi

javascript - node.js 中类实例之间的共享数组

转载 作者:搜寻专家 更新时间:2023-10-31 23:00:46 25 4
gpt4 key购买 nike

我在 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

为什么向一个实例添加元素会同时为两个实例添加元素? friend 数组似乎在实例之间“共享”。如何预防?

Demo here

最佳答案

删除行

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

改为将它们添加到构造函数中:

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

目前所有原型(prototype)共享同一个对象 friends

关于javascript - node.js 中类实例之间的共享数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25814271/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com