未捕获的TypeError:非法调用javascript

时间:2016-08-02 01:52:55

标签: javascript ecmascript-6

在此类中调用函数时如何修复非法调用

new FullScreen()。request(); //未捕获的TypeError:非法调用
   new FullScreen()。cancel(); //未捕获的TypeError:非法调用
   new FullScreen()。toggle(); //未捕获TypeError:非法调用

import validator from "Validator";

export default class FullScreen {
    constructor() {
        if (validator.checkValueType(Modernizr.fullscreen, "BOOLEAN") && Modernizr.fullscreen) {
            this.requestFullscreen = document.documentElement.requestFullscreen || document.documentElement.msRequestFullscreen ||
                document.documentElement.mozRequestFullScreen || document.documentElement.webkitRequestFullscreen;
            this.cancelFullScreen = document.cancelFullScreen || document.msCancelFullScreen || document.mozRequestFullScreen || document.webkitRequestFullscreen;
        } else {
            throw new UserException("Fullscreen not supported in this browser");
        }

    }

    request() {
        this.requestFullscreen();
    }

    cancel() {
        this.cancelFullScreen();
    }

    isFullScreen() {
        return document.isFullScreen || document.msIsFullScreen || document.mozIsFullScreen || document.webkitIsFullScreen;
    }

    toggle() {
        if (this.isFullScreen()) this.cancel();
        else this.request();
    }
}

2 个答案:

答案 0 :(得分:3)

没有测试,我最好的猜测是你丢失了文档的上下文。我建议将文档元素转换为您的方法。

import validator from "Validator";

export default class FullScreen {
    constructor() {
        if (!validator.checkValueType(Modernizr.fullscreen, "BOOLEAN") && Modernizr.fullscreen) {
            throw new UserException("Fullscreen not supported in this browser");
        }
    }

    request() {
        document.documentElement.requestFullscreen || document.documentElement.msRequestFullscreen ||
                document.documentElement.mozRequestFullScreen || document.documentElement.webkitRequestFullscreen;
    }

    cancel() {
        document.cancelFullScreen || document.msCancelFullScreen || document.mozRequestFullScreen || document.webkitRequestFullscreen;
    }

    isFullScreen() {
        return document.isFullScreen || document.msIsFullScreen || document.mozIsFullScreen || document.webkitIsFullScreen;
    }

    toggle() {
        if (this.isFullScreen()) this.cancel();
        else this.request();
    }
}

答案 1 :(得分:2)

Javascript中的

this与上下文相关。当您致电this.request()时,会转换为this.requestFullscreen()。在this.requestFullscreen = document.documentElement.requestFullscreenthis.requestFullscreen() != document.documentElement.requestFullscreen()时。相反,this.requestFullscreen() == document.documentElement.requestFullscreen.call(this)。换句话说,requestFullscreen函数需要documentElement作为this指针,但它会获得FullScreen实例,从而导致非法调用异常。要修复错误,您需要在构造函数中绑定上下文。