当子进程关闭时重新启动相同的功能

Re-launch the same function when a child-process is closed

我正在使用 js class,我希望当 child_process this.youtube 关闭时,函数 MainFunction() 再次重新启动;

我知道,如果你在其他函数中,你可以用 this.MainFunction() 调用这个函数,所以我尝试将它放入同一个函数中,但我得到了错误 this.MainFunction() is not a function

这是我的代码

const childprocess = require('child_process')
class Something {
    constructor(){

    }
    async MainFunction(){
        this.youtube=childprocess.spawn('C:/Program Files (x86)/Google/Chrome/Application/chrome.exe',["https://www.youtube.com/"]);
        this.youtube.on('close',function(){
            this.MainFunction()
        })
    }
}
module.exports = Something

因为this里面function所指的上下文。如果你想让它引用Something class,那么把回调改成箭头函数:

this.youtube.on('close',() => {
    this.MainFunction()
})

有关 this 工作原理的更多信息,请参阅 this great post.