【发布时间】:2013-10-18 01:27:23
【问题描述】:
所以我将大部分函数和变量组织成基于对象的小模块,如下所示:
module1: {
someVariable: false,
someFunction: function(e) {
do some stuff using someVariable
},
someFunction2: function(e) {
do some other stuff
}
}
我在各种事件期间将这些函数称为回调,如下所示:
$(function() {
$('.thing').on('mouseenter', module1.someFunction);
}
现在,在 someFunction 中,我希望“this”关键字引用包含该函数的对象。相反,它指的是触发函数的事件的 DOM 元素。无论如何我可以访问,比如函数包含对象中的 someVariable 变量,而不是编写 module1.someVariable?
【问题讨论】:
-
除非另有说明,否则事件处理程序始终具有触发事件的元素的上下文。您可以使用 Function.bind、$.proxy 或使用匿名函数并存储对所需上下文的引用来指定特定的上下文。
-
In Javascript, why is the “this” operator inconsistent? 的可能重复项,但您可能会发现我在 Understanding Javascript scope with “var that = this” 上的回答更直接地关注您的特定问题。
标签: javascript jquery