【问题标题】:How to make a javascript class array?如何制作一个javascript类数组?
【发布时间】:2020-01-13 19:50:19
【问题描述】:

我正在尝试在 javascrip 中启动一个类类型的 arerglo,以便我可以在我的 vuejs 组件上调用我的代码:

Class Person
export default class Person {

constructor(id, nombre, apellido) {
    this.id = id;
    this.nombre = nombre;
    this.apellido = apellido;
  }
}

PersonServicesClass:

import Person from '../model/person'


export default class PersonService {
person = new Array(Person)

constructor(
) {
    this.person = [];
}

add(id, nombre, apellido) {
    this.person.push(new Person(id, nombre, apellido));
    return this.person
  }
}

导入组件vue:

 <script>
 import PersonService from "../../Services/personservice";
 export default {
   name: "RegistroComponent",
     data: () => ({}),

     getData() {
       this.PersonService.add(1,"Steven","Chacon");
        }
     };

错误:

我会很有帮助的

【问题讨论】:

  • 完全删除person = new Array(Person) 行; this.person 无论如何都是一个不同的对象。
  • looooool 非常感谢,我从 typescript 到 javascrip

标签: javascript ecmascript-6 vue-cli vue-cli-3


【解决方案1】:

删除person = new Array(Person)这一行

【讨论】:

    【解决方案2】:

    JS 中的 Person 类:

    var Person = function (firstname, lastname, age) {
      this.firstName = firstname;
      this.lastName = lastname;
      this.age = age;
    
      this.setAge = function (age) {
        this.age = age;
      };
    
      this.toString = function () {
        return ["Hi ! I'm ", this.firstName, " ", this.lastName, " and I'm ", this.age, " year old."].join("");
      };
    };
    

    或使用 Object.prototype

    var Person = function (firstname, lastname, age) {
      this.firstName = firstname;
      this.lastName = lastname;
      this.age = age;
    };
    
    // Prototypes are better for performances if you have many call of this method
    Person.prototype.setAge = function (age) {
      this.age = age;
    };
    
    Person.prototype.toString = function () {
      return ["Hi ! I'm ", this.firstName, " ", this.lastName, " and I'm ", this.age, " year old."].join("");
    };
    

    这是一个工作笔:CodePen

    【讨论】:

      【解决方案3】:

      在您编写的 PersonServicesClass 中

        person = new Array(Person)
      

      你写的构造函数内部

        this.person = [];
      

      这两者是冲突的。所以请删除

        person = new Array(Person)
      

      希望它能完美运行。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-01-29
        • 2023-03-20
        • 1970-01-01
        • 2023-04-10
        • 1970-01-01
        • 2012-10-23
        • 1970-01-01
        相关资源
        最近更新 更多