【问题标题】:fill an array with class instances用类实例填充数组
【发布时间】: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


    【解决方案1】:

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

    【讨论】:

    • 这就是问题所在。它现在可以工作了,谢谢一百万
    猜你喜欢
    • 2016-07-24
    • 1970-01-01
    • 1970-01-01
    • 2019-12-15
    • 2015-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-11
    相关资源
    最近更新 更多