我陷入了填充类实例数组的困境。长话短说,我创建了一个类人(上面带有属性和函数),我想填充一个人类实例数组,只需将其添加到该人类的“新”实例数组中即可。 结果,数组中充满了许多指向最后创建的实例的元素。
这里是一个简化的示例代码。 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());
我的错在哪里?
预先感谢您的帮助
答案 0 :(得分:1)
您有一个不属于类的变量,每次创建一个新的person实例时,该变量都会重置。而是使它成为类人的财产,因此看起来像这样:
class Person {
constructor(name, age){
this.p = {
name, age
}
}
greeting(){
console.log("Hi, I'm ", this.p);
}
}
您还可以将它们拆分为自己的变量:
class Person {
constructor(name, age){
this.name = name;
this.age = age;
}
greeting(){
console.log("Hi, I'm ", this.name, this.age);
}
}