我希望能够用他们的id(数组中的位置)来控制构造函数我不确定是否有可能杀死单个构造函数的进程,但这正是我正在寻找的。我需要能够在列表中停止并启动带有索引的构造函数。
class Worker {
constructor(id, fname, lname) {
this.id = id;
this.fname = fname;
this.lname = lname;
this.age = age;
}
if (this.id===1) {
process.exit()
} else {
console.log(fname+" "+lname+" "+age);
}
}
let fnames = ["johnathan", "richard", "david", "hayden", "josh", "harry", "raymond", "braylon", "john", "kent"];
let lnames = ["smith", "scott", "richards", "stine", "davidson", "dominic", "weltz", "joseph", "daigle", "goodman"];
for (let i = 0; i < 10; i++) {
let worker = new Worker(i, fnames[i], lnames[i]);
workers.push(worker);
}
答案 0 :(得分:0)
我并不完全清楚你的意思是什么&#34;杀死构造函数的过程。&#34; JavaScript是一种垃圾收集语言,因此运行时负责在不再引用它时为您删除对象实例。
请参阅此帖子,虽然不是您的副本,但类似:JavaScript: Create and destroy class instance through class method
但是,如果您想在构造时基于其id
值触发某个方法调用,则可以这样做:
class Worker {
constructor(id, fname, lname) {
this.id = id;
this.fname = fname;
this.lname = lname;
this.age = age;
if (this.id===1) {
this.someMethod();
} else {
console.log(fname+" "+lname+" "+age);
}
}
someMethod(){
// do the thing here
}
}