处理jQuery和Object的"this"之间的冲突 [英] Dealing with clash between jQuery and Object's "this"
问题描述
我正在实例化一个对象,该对象创建一个DOM元素并存储 jQuery对象作为其属性之一,例如:
this.element = $("<div></div>");
我注意到在建立事件时,jQuery对this
上下文的重写会导致问题,例如,如果您尝试应用以下内容:
this.element.click(function() {
this.someObjectMethod();
});
内部this
现在适用于DOM元素,而不是原始Object.为了克服这个问题,我可以执行以下操作:
var _this = this;
this.element.click(function() {
_this.someObjectMethod();
});
我想知道,这是不好的做法吗,还有更好的方法吗?我看了一些关于apply
和call
的jQuery文档,但我'不确定他们是否会在这种情况下提供帮助.
此外,我正在使用 Resig的'简单继承'Class 改变您的答案.
更新是关于$.proxy
的答案,这些似乎是合理的解决方案,但是您将失去引用DOM元素的能力.
您可以使用 $ .proxy( ):
this.element.click($.proxy(function() {
this.someObjectMethod();
}, this));
它返回一个函数,该函数将始终在您在第二个参数中指定的对象的上下文中被调用(在本例中为外部this
).
$.proxy()
还对事件处理程序强制执行一种特殊情况:如果稍后将原始的,未代理的方法传递给off()
或unbind()
,则即使您未直接指定代理处理程序,也将透明地将其删除. /p>
I'm instantiating an Object which creates a DOM element and stores a jQuery Object as one of it's properties, e.g.:
this.element = $("<div></div>");
I noticed that when establishing events, jQuery's rewriting of thethis
context can cause issues, such as if you tried to apply the following:
this.element.click(function() {
this.someObjectMethod();
});
The inner this
now applies to the DOM element and not the original Object. To overcome this, I can do the following:
var _this = this;
this.element.click(function() {
_this.someObjectMethod();
});
I'm wondering, is bad practice and is there a better way? I've looked at some jQuery docs on apply
and call
but I'm not sure they'd help in this situation.
Additionally, I'm using Resig's 'simple inheritence 'Class, which might make a difference to your answers.
Update on seeing the $.proxy
answers, these seem reasonable solutions, however you then lose the ability to reference the DOM element.
You can use $.proxy():
this.element.click($.proxy(function() {
this.someObjectMethod();
}, this));
It returns a function that will always be invoked in the context of the object you specify in the second argument (in our case, the outer this
).
$.proxy()
also enforces a special case with event handlers: if you pass the original, unproxied method to off()
or unbind()
later, the proxied handler will be transparently removed even though you did not specify it directly.
这篇关于处理jQuery和Object的"this"之间的冲突的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!