Cannot read property stop of undefined - when calling a static method from inside class

空扰寡人 提交于 2020-01-25 07:27:11

问题


For some reason, when I run this code, even without first calling the startRecording method it gives me this error right after the page has loaded.

Uncaught TypeError: Cannot read proporty 'stop' of undefind.

I think it has something to do with scope but I'm not sure. The startRecording method works fine but it finds a problem in stopRecording.

RecorderClass

class RecorderClass
{
    constructor() {
        this.rec = ''
    }

    static startRecording() {
        this.rec = new Recorder()
        this.rec.record()
    }

    static stopRecording() {
        this.rec.stop() // stop() of undefined
    }
}

app.js

import RecorderClass from './RecorderClass.js'
recButton.addEventListener("click", RecorderClass.startRecording())

回答1:


You should declare Recorder reference in the scope of class, so that stop recording method can use it.

 public class RecorderClass
{
    static Recorder rec;
    public RecorderClass()
    {
    }

    public static void startRecording()
    {
        rec = new Recorder();
        rec.record();
    }

    public static void stopRecording()
    {
        rec.stop();// stop() of undefined
    }
}


来源:https://stackoverflow.com/questions/59142485/cannot-read-property-stop-of-undefined-when-calling-a-static-method-from-insid

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!