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

lkr*_*aav 20 javascript jquery

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

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

Ale*_*rge 44

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

var that = this;
...

form.find(':radio').change(function () {
    that.note.vacancy = $(this).attr('value');
});
Run Code Online (Sandbox Code Playgroud)

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


小智 5

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

  • 我看到使用$ .proxy作为一个更优雅的解决方案,但是想要理解:这是一个更好的解决方案,是否已被接受作为答案?有什么不同? (2认同)