jQuery:如何访问父函数“this”来自匿名函数? [英] jQuery: how to access parent function "this" from inside anonymous function?

查看:76
本文介绍了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;
});
...

是否可以从更改中访问this.note( )处理程序没有定义mynote?

Is it possible to access "this.note" from the change() handler without defining "mynote"?

推荐答案

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

I use a pattern like this so I can access anything in the enclosing scope:

var that = this;
...

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

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

I am a fan of this pattern because it makes the code a little more readable. In my opinion, it is clear what it being accessed is part of the enclosing scope (as long as the usage of that is consistent).

这篇关于jQuery:如何访问父函数“this”来自匿名函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆