[英]jQuery: how to access parent function “this” from inside anonymous function?
...
$.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');
});
我是这种模式的粉丝,因为它使代码更具可读性。 在我看来,很显然它被访问时封闭范围的一部分(只要使用that
是一致的)。
使用$.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.
它没有专门的语言机制。 共同模式是到存储this
在本地(闭合)变量(通常命名为self
或that
外部函数的):
var self = this;
var innerFunction = function() {
self.x = 1;
};
您可以像这样绑定父对象的上下文。
form.find(':radio').change(function(that) {
var vacancy = $(this).attr('value');
that.note.vacancy = vacancy;
}.bind(null,this));
检查一下 - 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);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.