我有一个像这样的听众:
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/