简体   繁体   English

创建空构造函数并在 class 中初始化数组时出现问题

[英]Problems creating an empty constructor, and initializing an array in a class

I have tried moving the array before, after the constructor.我之前尝试过在构造函数之后移动数组。 I am pretty sure I have the syntax wrong at this point, I have tried researching for quite some time without luck.我很确定此时我的语法错误,我已经尝试研究了很长一段时间但没有运气。 Any help would be appreciated.任何帮助,将不胜感激。

class dataService {
  constructor() {
  }

  //I need to be able to initialize this array of objects and create an empty constructor which does nothing

  var data = [ // Error: Construcotr, method, accessor, or property was expected
  name1 = { name: "Mitchell", gender: "male", address: "201 Burns Street East", age: 20, phoneNumber: "905-550-7379" },
  name2 = { name: "Bob", gender: "male", address: "555 Hello Street", age: 25, phoneNumber: "123-456-7891" },
  name3 = { name: "Gillian", gender: "female", address: "457 Baker Street", age: 23, phoneNumber: "555-111-999" }
];

getData(numRecords) {
  numRecords = numRecords || undefined;
  if (numRecords == undefined) {
    return data;
  }
};


}

Hey my friend you have several errors on how you define properties of classes, i recommend to you to check out javascript classes嘿,我的朋友,你在如何定义类的属性方面有几个错误,我建议你查看 javascript 类

mozilla javscript classes documentation and examples mozilla javscript 类文档和示例

first you have a mistake on array definition, this is the right way:首先你在数组定义上有错误,这是正确的方法:

  this.data = [ 
  { name: "Mitchell", gender: "male", address: "201 Burns Street East", age: 20, phoneNumber: "905-550-7379" },
   { name: "Bob", gender: "male", address: "555 Hello Street", age: 25, phoneNumber: "123-456-7891" },
  { name: "Gillian", gender: "female", address: "457 Baker Street", age: 23, phoneNumber: "555-111-999" }
];

Second you can initialize you array on the constructor and assign to the class with the "this" keyword.其次,您可以在构造函数上初始化数组并使用“this”关键字分配给 class。

I made a working example for you base on your code:我根据您的代码为您做了一个工作示例:

js online example js在线示例

Peace, mis perros !和平,错误的人!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM