es6类和"this"与事件处理程序 [英] es6 classes and "this" with event handlers

查看:66
本文介绍了es6类和"this"与事件处理程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

玩一些es6,遇到了一个我不确定如何解决的问题.考虑以下

playing around with some es6 and ran into an issue i'm not sure how to solve. consider the following

class Foo {
 constructor ( ) {
   window.addEventListener('scroll', this.watch);
 }

 watch ( ) {
   console.log(this);
 }
}

watch内,thiswindow对象,如预期的那样.但是,我怎么指代Foo?目前,我可以通过bind this.watch.bind(this)解决这个问题,但是我很想知道是否还有一种更合适的" ES6方法来实现这一目标.

Inside of watch, this is the window object, as expected. But how do i refer to Foo? Currently I get around this with bind this.watch.bind(this) but i'd love to know if there is a more "proper" ES6 way to get this going.

推荐答案

您可以使用箭头功能.

箭头函数表达式(也称为胖箭头函数) ) 有一个 与函数表达式相比语法更短,并且词法绑定 此值.

An arrow function expression (also known as fat arrow function) has a shorter syntax compared to function expressions and lexically binds the this value.

window.addEventListener('scroll', () => this.watch());

这篇关于es6类和"this"与事件处理程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆