【发布时间】:2014-02-25 09:15:55
【问题描述】:
我对原型 JS 编码和回调有一个小问题。好像不能正常工作。
这是我的示例:
var hl = new HeaderLogin;
hl.drawPanel();
var HeaderLogin = function(elem) {
this.init = true;
this.jsvh = JSViewHandler.getInstance();
};
HeaderLogin.prototype.drawPanel = function() {
var self = this;
...
this.jsvh.get({
...
'callback': function(rsp, templates) {
...
$('#jsview_user_login_form').ajaxForm({success: asd});
}
});
function asd(rspJSON, statusText, xhr, $form) {
self.showResponse(rspJSON, statusText, xhr, $form);
}
};
HeaderLogin.prototype.showResponse = function(rspJSON, statusText, xhr, $form) {
if (typeof this.init === 'undefined') {
alert('not an object');
}
...
}
我必须在表单发送后调用showResponse 函数,但如果我使用{success: self.showResponse},init 将不存在。它看起来像一个静态调用,我无法从构造函数访问任何变量。如果我创建一个本地 asd 函数并将其用作成功回调,showRespons 将知道构造函数变量。
我不想使用这个额外的功能,如果您对此问题有任何解决方案,请告诉我!
非常感谢各位! :)
解决方案:
成功:self.showResponse.bind(self)
【问题讨论】:
-
var hl = new HeaderLogin();
-
试试
success: self.showResponse.bind(self) -
哇哈哈,你就是男人!它的工作,谢谢! :)
标签: javascript object callback prototype ajaxform