避免 var _this = this;编写 jQuery 事件处理程序时
这不是一个非常重要的问题,但我们开始了..
如何避免在 jQuery 事件处理程序中使用 var _this = this ? 即我不喜欢这样做:
var _this = this;
$(el).click(function (event) {
//use _this to access the object and $(this) to access dom element
});
以下两种方式并不理想
$(el).click($.proxy(function (event) {
//lost access to the correct dom element, i.e. event.target is not good enough (see http://jsfiddle.net/ne3n3/1/)
}, this));
$(el).click({_this: this}, function (event) {
//have access to $(this) and event.data._this, but it seems too verbose
})
理想情况下我想做类似的事情
$(el).click(function (event) {
this.method(); // this is accessing the object
event.realTarget; // this is accessing the dom element
}, this); // <= notice this
Not a very important question, but here we go..
How do you avoid using var _this = this in jQuery event handlers?
i.e. I don't like doing:
var _this = this;
$(el).click(function (event) {
//use _this to access the object and $(this) to access dom element
});
The following 2 ways are not ideal
$(el).click($.proxy(function (event) {
//lost access to the correct dom element, i.e. event.target is not good enough (see http://jsfiddle.net/ne3n3/1/)
}, this));
$(el).click({_this: this}, function (event) {
//have access to $(this) and event.data._this, but it seems too verbose
})
Ideally I would like to do something like
$(el).click(function (event) {
this.method(); // this is accessing the object
event.realTarget; // this is accessing the dom element
}, this); // <= notice this
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
http://api.jquery.com/event.currentTarget/ 说:
http://jsfiddle.net/ne3n3/2/
http://api.jquery.com/event.currentTarget/ says:
http://jsfiddle.net/ne3n3/2/
我不完全确定我理解正确,但是如果您想要的是对创建回调函数时所在函数的引用,您可以这样做(尽管这并不能完全节省您的时间)任何打字):
I'm not entirely sure I understand you right, but if what you want is a reference to the function you were in when creating the callback function you could do it like this (although it's not exactly saving you any typing):
您不能将变量
this
同时分配给对象和 DOM 元素。我的建议是将对象分配给与this
不同的变量。访问对象和 DOM 元素的最佳方法如下:
或者可能像这样:
在点击事件处理函数中使用除
this
之外的变量也会使您的代码更清晰,因为大多数人会期望this
引用 DOM 元素,并且与您的自定义对象无关。You cannot assign the variable
this
to both the object and the DOM element. My recommendation is to assign the object to a different variable thanthis
.The best way to access both the object and the DOM element would be something like the following:
or maybe like this:
Using a variable other than
this
inside the click event handling function will also make your code clearer, since most people would expectthis
to reference the DOM element and have nothing to do with your custom object.