jQuery:如何从匿名函数内部访问父函数“this”?

... $.fn.annotateEdit = function(image, note) { if (note) { this.note = note; } else { var newNote = new Object(); newNote.id = "new"; this.note = newNote; } } ... var mynote = this.note; form.find(':radio').change(function() { var vacancy = $(this).attr('value'); mynote.vacancy = vacancy; }); ... 

是否可以从change()处理程序访问“this.note”而无需定义“mynote”?

我使用这样的模式,所以我可以访问封闭范围内的任何内容:

 var that = this; ... form.find(':radio').change(function () { that.note.vacancy = $(this).attr('value'); }); 

我是这种模式的粉丝,因为它使代码更具可读性。 在我看来,很明显它被访问的是封闭范围的一部分(只要它的使用是一致的)。

使用$.proxy将其绑定到函数…

  // Returns a function-------v form.find(':radio').change( $.proxy(function() { var vacancy = $(this).attr('value'); mynote.vacancy = vacancy; }, this) ); // ^---- ...that has its "this" value set as this argument. 

它没有专门的语言机制。 常见的模式是将它存储在外部函数的本地(闭包)变量(通常命名为selfthat )中:

 var self = this; var innerFunction = function() { self.x = 1; }; 

检查一下 – http://api.jquery.com/bind/和“传递事件数据”你可以这样做:

 form.find(':radio').bind("change", { context : this }, function(event){ console.log(event.data.context); console.log(event.data.context.note); }); 

您可以像这样绑定父对象的上下文。

 form.find(':radio').change(function(that) { var vacancy = $(this).attr('value'); that.note.vacancy = vacancy; }.bind(null,this));