在此类中调用函数时如何修复非法调用
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();
}
}
答案 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)
this
与上下文相关。当您致电this.request()
时,会转换为this.requestFullscreen()
。在this.requestFullscreen = document.documentElement.requestFullscreen
,this.requestFullscreen() != document.documentElement.requestFullscreen()
时。相反,this.requestFullscreen() == document.documentElement.requestFullscreen.call(this)
。换句话说,requestFullscreen
函数需要documentElement
作为this
指针,但它会获得FullScreen
实例,从而导致非法调用异常。要修复错误,您需要在构造函数中绑定上下文。