jQuery 'this' 回调中
jQuery 'this' in callback
我的 filepicker.io 对话框正常,但在成功回调时我似乎失去了我的 'this' 上下文。
所以我的代码是这样的
var fileProcess ={
saveFileInfo: function () {
.....process info here
},
selectFile: function () {
filepicker.pick({ mimetype: 'image/*' }, function (Blob) {
this.saveFileInfo();
});
}
}
那么有没有类似 "context: this" 我可以在 ajax 通话中做的事情?
尝试在回调之外创建一个名为 self
或 me
的新变量,并将其设置为 this
的当前值。然后,您使用闭包,这样您就可以通过 me
或 self
.
从回调中访问 this
赞:
this.mesg = "Hello";
var self = this;
function handler() {
alert(self.mesg);
}
上下文切换后...
handler(); // Will alert 'Hello'
编辑:哦,疯了……刚意识到那行不通……试试:
function handler() {
alert(this.msg);
}
var newHandler = handler.bind(this);
稍后...
newHandler();
Function.prototype.bind()
接受一个对象,returns 接受一个函数。每当调用返回的函数时,传递给 bind()
的对象将用作 this
.
我的 filepicker.io 对话框正常,但在成功回调时我似乎失去了我的 'this' 上下文。
所以我的代码是这样的
var fileProcess ={
saveFileInfo: function () {
.....process info here
},
selectFile: function () {
filepicker.pick({ mimetype: 'image/*' }, function (Blob) {
this.saveFileInfo();
});
}
}
那么有没有类似 "context: this" 我可以在 ajax 通话中做的事情?
尝试在回调之外创建一个名为 self
或 me
的新变量,并将其设置为 this
的当前值。然后,您使用闭包,这样您就可以通过 me
或 self
.
this
赞:
this.mesg = "Hello";
var self = this;
function handler() {
alert(self.mesg);
}
上下文切换后...
handler(); // Will alert 'Hello'
编辑:哦,疯了……刚意识到那行不通……试试:
function handler() {
alert(this.msg);
}
var newHandler = handler.bind(this);
稍后...
newHandler();
Function.prototype.bind()
接受一个对象,returns 接受一个函数。每当调用返回的函数时,传递给 bind()
的对象将用作 this
.