我想要实现的是:
allProject
数组。._hours
已在数组中之后显示其中的某些变量。我的代码包括:
//Declare Array that will Host Projects
const allProjects = [];
//Create Parent Class that creates objects (Project)
class Project {
constructor(projTitle, projDescription, projHours) {
//Declare variables
this._name = projTitle;
this._description = projDescription;
this._hours = projHours;
//Send newly constructed object directly to next space in array.
allProjects.push(constructor(projTitle, projDescription, projHours));
}
}
//Create new object.
const DataEntry = new Project('Data Entry', 'Enter Data into Amazon', '4 Hours');
//Display the name variable housed in the object that was pushed into allProjects array.
console.log(allProjects[0].DataEntry._name);
输出看起来像这样:
/Users/ervin/WebstormProjects/untitled/Project Management.js:30
console.log(allProjects[0].DataEntry._name);
^
TypeError: Cannot read property '_name' of undefined
at Object.<anonymous> (/Users/ervin/WebstormProjects/untitled/Project
Management.js:30:38)
at Module._compile (module.js:652:30)
at Object.Module._extensions..js (module.js:663:10)
at Module.load (module.js:565:32)
at tryModuleLoad (module.js:505:12)
at Function.Module._load (module.js:497:3)
at Function.Module.runMain (module.js:693:10)
at startup (bootstrap_node.js:191:16)
at bootstrap_node.js:612:3
Process finished with exit code 1
任何帮助都被考虑和赞赏。让我知道是否需要澄清任何事情。
答案 0 :(得分:1)
您可以像这样访问._name
:allProjects[0]._name
但是您实际上是在推错方向。调用new Project(...)
后,您将收到参数,因此按如下所示进行推送:
//Declare Array that will Host Projects
const allProjects = [];
class Project {
constructor(projTitle, projDescription, projHours) {
this._name = projTitle;
this._description = projDescription;
this._hours = projHours;
}
}
//Create new object.
const DataEntry = new Project('Data Entry', 'Enter Data into Amazon', '4 Hours');
allProjects.push(DataEntry)
//Display the name variable housed in the object that was pushed into allProjects array.
console.log(allProjects[0]._name)
完全没有经过测试,但是应该可以使用!
答案 1 :(得分:1)
在构造函数中更新此行
allProjects.push(this);
我已经对其进行了测试,它可以按预期工作。