Typescript类中Javascript的范围“ this”

我正在尝试在切换视频(播放/暂停)时更改视频的自定义图标。

ngAfterViewInit() {
 const vdoCont = document.querySelector('.video-player');
 const vdo = vdoCont.querySelector('video');
    vdo.addEventListener('play',() => {
     console.log(this) // Here "this" refers to typescript class
     this.updateVdoIcon(this);
    });
    vdo.addEventListener('pause',() => {
     console.log(this) // Here "this" refers to typescript class
     this.updateVdoIcon(this);
    });
}

updateVdoIcon(videoElment: any) {
    console.log(videoElment); // Expecting this to be video element instead of typescript class
  }

我试图将箭头功能更改为JavaScript功能,但是在这里我无法使用我的“ updateVdoIcon”功能。

vdo.addEventListener('play',function() {
      this.updateVdoIcon(this); // Property 'updateVdoIcon' does not exist on type 'HTMLVideoElement'
});

我知道我可以使用匿名函数(如下所示)并在那里更新图标,但是如果我想在函数中分离很多代码怎么办

vdo.addEventListener('play',function() {
 this.paused ? console.log('Play icon') : console.log('Pause icon')
});
zhuzheqi2096409 回答:Typescript类中Javascript的范围“ this”

您可以尝试通过使用ElementRef来访问元素,然后绑定事件。

源代码来自:https://stackoverflow.com/a/41610950/9380944答案。

import { AfterViewInit,Component,ElementRef} from '@angular/core';

constructor(private elementRef:ElementRef) {}

ngAfterViewInit() {
  this.elementRef.nativeElement.querySelector('my-element')
                                .addEventListener('click',this.onClick.bind(this));
}

onClick(event) {
  console.log(event);
}
,

调用事件侦听器处理程序时,不会在Component范围内调用它。因此,this不返回组件,而是返回控件元素。

您需要将监听器与this绑定。

vdo.addEventListener('play',(function() {
      this.updateVdoIcon(this);
}).bind(this));

请参阅文档here


您可以通过将其分隔为onClick函数来使其更清晰。

onClick() {
  this.updateVdoIcon(this);
}

initialize() {
  vdo.addEventListener('play',this.onClick.bind(this));
}

或者,您可以捕获this作为组件并传递给事件侦听器。

let self = this;

vdo.addEventListener('play',function() {
      self.updateVdoIcon(this);
});
,

您可以在回调中传递event.currentTarget,这将是您定义事件监听器的元素:

vdo.addEventListener('play',(event) => {
     this.updateVdoIcon(event.currentTarget);
});

在您的代码段中,this将成为箭头功能中的 词汇 this。它从词法范围(即类实例)中捕获this上下文。

,

这是您的解决方案

ngAfterViewInit() {
const vdoCont = document.querySelector('.video-player');
const vdo = vdoCont.querySelector('video');
const that = this;
   vdo.addEventListener('play',function(){
    console.log(this) // Here "this" refers to typescript class
    that.updateVdoIcon(this);
   });
   vdo.addEventListener('pause',function(){
    console.log(this) // Here "this" refers to typescript class
    that.updateVdoIcon(this);
   });

}

updateVdoIcon(videoElment:任何){        console.log(videoElment); //期望它是视频元素,而不是typescript类      }

本文链接:https://www.f2er.com/3168820.html

大家都在问