[英]How to create a new class instance from within an instance?
我想寫一個小小的“生命模擬”,生命體可以在其中自我繁殖。 我希望每個類實例都能夠創建更多實例,例如克隆/復制自身。 我確實知道如何從班級外部創建一個新實例,但我希望班級自己完成。
class Life{
constructor(){
this.age = 0;
}
frame_loop(){
this.age ++;
if (this.age == 18){
this.reproduce();
}
}
reproduce(){
// obviously does not work
this.new();
}
}
let bacteria = new Life();
我不想在課外創造新的生活,比如
let bacteria1 = new Life();
任何幫助表示贊賞。
你可以做這樣的事情。 有一個 children 屬性,只要年齡合適,就會創建新的 Life()
class Life{ children = []; constructor(){ this.age = 0; } frame_loop(){ this.age ++; if (this.age == 18){ this.reproduce(); } } reproduce(){ console.log("new life") this.children.push(new Life()); } } let bacteria = new Life(); for(var i = 0; i < 100; i++){ bacteria.frame_loop(); }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.