如何解决角度:this.confirmPosition 不是一个函数
我试图检测用户何时退出全屏,例如使用 esc 按钮, 当用户退出全屏模式时,我需要制作一个弹出对话框
代码如下:
ngOnInit(): void {
const document = window.document;
if (document.addEventListener)
{
document.addEventListener('fullscreenchange',this.exitHandler,false);
document.addEventListener('mozfullscreenchange',false);
document.addEventListener('MSFullscreenChange',false);
document.addEventListener('webkitfullscreenchange',false);
}
}
exitHandler(){
const document:any = window.document;
if (document.webkitIsFullScreen === false){
this.confirmPosition();
}else if (document.mozFullScreen === false){
this.confirmPosition();
}else if (document.msFullscreenElement === false){
this.confirmPosition();
}
}
confirmPosition() {
this.confirmationService.confirm({
message: 'Do you want to delete this record?',header: 'Delete Confirmation',icon: 'pi pi-info-circle',accept: () => {
},reject: () => {
},key: "positionDialog"
});
}
ERROR TypeError: this.confirmPosition 不是函数
注意:我使用的是primeng对话框,但这当然与confirmPosition中的内容无关,因为如果我将内容更改为这样:
confirmPosition() {
console.log('hello ');
}
它仍然抱怨同样的错误。
解决方法
您需要绑定这个。
document.addEventListener('fullscreenchange',this.exitHandler.bind(this),false);
说明:
在js中,调用函数时,在函数体内部,执行时,this指针将是调用该函数的对象。 在这种情况下,文档对象正在调用您在注册事件侦听器时提供的回调。如果你想改变它,你可以使用 fnc1.bind(object)
显式地将一个对象绑定到一个函数然而,js 中的箭头函数会自动绑定到词法作用域。
试试下面这个例子并观察控制台,你会意识到发生了什么
import { Component,OnInit,VERSION } from "@angular/core";
@Component({
selector: "my-app",templateUrl: "./app.component.html",styleUrls: ["./app.component.css"]
})
export class AppComponent implements OnInit {
ngOnInit() {
// Here,this "pointer"inside the function body will be document object (since document object called it)
document.addEventListener("click",function() {
console.log("Inline function",this);
});
// Here,it will be the same as in prevoius case
document.addEventListener("click",this.externalFunction);
// Here,we will bind this pointer explicitly to a specific object (in this caase its AppComponent instance)
document.addEventListener("click",this.externalFunctionWithBind.bind(this));
// Arrow function will automatically bind this to an object that is in the lexical scope
// Lexical scope is the one that is arounding it and it this case its AppComponent instance
document.addEventListener("click",() => {
console.log("Arrow function",this);
});
}
inlineFunction() {
console.log("Inline Function",this);
}
externalFunction() {
console.log("External Function",this);
}
externalFunctionWithBind() {
console.log("External Function With Bind",this);
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。