arrays - 用类实例填充数组

标签 arrays node.js class deep-copy shallow-copy

我在填充类实例数组时遇到了困难。为了长话短说,我创建了一个 person 类(其上有属性和函数),并且我想填充一个 person 实例数组,只需插入该 person 类的数组"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 实例时,它都会被重置。相反,让它成为类 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/

相关文章:

java - 尝试用对象数组中的 double 值替换字符串

javascript - 如何使用 Node js 和 puppeteer 抓取图像 src url

node.js - 不能在 Node 中说 Hello World

node.js - Node CLI argv(参数数组)为空

java 类和对象没有正确的输出

javascript - 使用索引和值将元素添加到现有对象

javascript - 针对另一个对象数组循环遍历对象数组

与数组一起使用的 C 语言指针

c# - 静态类与具有构造函数性能的类

PHP:如何创建对象变量?