javascript - 控制回调的 "this"上下文

标签 javascript jquery listener this

我有一个像这样的听众:

this.frame.on('touchend', self.findClosestSlide);

我需要这样,而不是在匿名函数中,以便稍后能够使用函数名称取消绑定(bind)。

我的问题是,一旦我进入findClosestSlide功能,我的this对象逻辑上变成 this.frame .

如何访问原始this ,或者我如何控制发送到回调函数的上下文? (不使用匿名函数)

最佳答案

您可以使用 Function.bind() 或 $.proxy() 将自定义上下文传递给回调,例如

跨浏览器,使用$.proxy()

this.frame.on('touchend', $.proxy(self.findClosestSlide, self));

IE9+ ,使用function.bind()

this.frame.on('touchend', self.findClosestSlide.bind(self));
为什么?因为默认情况下,事件处理程序中的 this 将引用事件所针对的元素

关于javascript - 控制回调的 "this"上下文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22384288/

相关文章:

javascript - 使用 html Mailto : not working 向多个收件人发送电子邮件

javascript - 无法在anglar4中导入RX

javascript - 检查元素是否属于父 HTML 标记

java - 可以在 Listener 类中使用 Adapter 吗?

javascript - 是否可以为未加载的视频提供备用 anchor 链接?

javascript - 在 react-native 中通过 PUT 方法上传文件

jquery - HTML 设置激活并具有不同的背景颜色

javascript - 将初始化绑定(bind)到动态创建的元素

java - 如何在 Kotlin 中使用回调?

javascript - 将监听器附加到多个 child