我被困填补了一系列的类实例。长话短说,我创建了一个类人(上面带有属性和函数),我想填充一个人类实例数组,只需将其添加到该人类的数组“ new”实例中即可。
结果,数组中充满了许多指向最后创建的实例的元素。

这里是一个简化的示例代码。
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());


我的错在哪里

在此先感谢您的帮助

最佳答案

您有一个不属于类的变量,每次创建新的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);
  }
}

关于arrays - 用类实例填充数组,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/52917012/

10-11 22:54
查看更多