版权声明:@copyright by taorui https://blog.csdn.net/weixin_42541498/article/details/80926017
用框架angular写代码时:
ngOnInit(){
this.boldBtn.nativeElement.addEventListener( 'mouseover',this.showItems);
}
getItems(){
}
showItems(){
this.getItems();//这里的this指向一个button
}
错误:
控制台报错:this.getItems is not function
原因:
this.showItems的this指向触发事件的DOM对象。
当函数被当做事件处理函数时,函数里的这个指向触发事件的DOM对象,这里指向一个按钮对象。
所以this.getItems()是不存在的。
解决办法:
this.boldBtn.nativeElement.addEventListener('mouseover',() => this.showItems());
使用箭头函数,箭头函数里的this继承自父级作用域的this,this.showItems()的this指向angular的class实例
showItems()函数里的this也指向angular的class实例,this.getItems()就拿得到了。