避免var _this = this; 在编写jQuery事件处理程序时

Kar*_*lis 6 javascript syntax jquery

这不是一个非常重要的问题,但我们走了......

你如何避免在jQuery事件处理程序中使用var _this = this?即我不喜欢这样做:

var _this = this;
$(el).click(function (event) {
  //use _this to access the object and $(this) to access dom element
});
Run Code Online (Sandbox Code Playgroud)

以下两种方式并不理想

$(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
})
Run Code Online (Sandbox Code Playgroud)

理想情况下,我想做点什么

$(el).click(function (event) {
  this.method(); // this is accessing the object
  event.realTarget; // this is accessing the dom element
}, this); // <= notice this
Run Code Online (Sandbox Code Playgroud)

biz*_*lop 2

http://api.jquery.com/event.currentTarget/说:

“这个属性通常等于函数的 this。”

http://jsfiddle.net/ne3n3/2/