【发布时间】:2018-10-21 15:41:06
【问题描述】:
我在填充类实例数组时遇到了困难。长话短说,我创建了一个人类(上面有属性和函数),我想填充一个人的实例数组,只需推入该人的类的数组“新”实例。 结果,数组中充满了许多指向最后创建的实例的元素。
这里是一个简化的示例代码。 https://repl.it/@expovin/ArrayOfClassInstances
let p={
name:"",
age:""
}
class Person {
constructor(name, age){
p.name=name;
p.age=age;
}
greeting(){
console.log("Hi, I'm ",p);
}
gatOler(){
p.age++;
}
}
module.exports = Person;
它是这样使用的:
let person = require("./Person");
var crowd = [];
console.log("Let's create an instance of Person in the crowd array");
crowd.push(new person("Vinc", 40));
console.log("Instance a is greeting");
crowd[0].greeting();
console.log("Let's add a new instance of Person as next element in the same array");
crowd.push(new person("Jack", 50));
crowd[1].greeting();
console.log("I expect to have two different people in the array");
crowd.forEach( p => p.greeting());
我的错在哪里?
提前感谢您的帮助
【问题讨论】:
标签: arrays node.js class deep-copy shallow-copy