看下面红色代码中的this.bind怎么定义,现在这里的this是代表 var xm = new XMLHttpRequest();中的xm,但是我现在想得到this.bind(this, function () {}中蓝色字中的this是实例AjaxRequest的对象引用,比如:var aa=new AjaxRequest(method, url, data, callback);我想蓝色的this是aa这个实例后的对象。但是不知道怎么搞。
function AjaxRequest(method, url, data, callback) {
this.method = method;
this.url = url;
this.data = data;
this.callback = callback;
this.send = function () {
var xm = new XMLHttpRequest();
this.url = (data.length > 0 && this.method == "get") ? this.url + "?" + this.data : this.url;
xm.open(this.method, this.url, true);
if (this.method == "get") {
xm.setRequestHeader("If-Modified-Since", 0);
} else {
xm.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
}
xm.onreadystatechange = this.bind(this, function () {
if (xm.readyState == 4 && xm.status == 200)
this.callback(xm.responseText);
});
if (this.method == "get") {
xm.send();
}
else {
xm.send(this.data);
}
}
}
function AjaxRequest(method, url, data, callback) {
this.method = method;
this.url = url;
this.data = data;
this.callback = callback;
this.send = function () {
var xm = new XMLHttpRequest();
this.url = (data.length > 0 && this.method == "get") ? this.url + "?" + this.data : this.url;
xm.open(this.method, this.url, true);
if (this.method == "get") {
xm.setRequestHeader("If-Modified-Since", 0);
} else {
xm.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
}
xm.onreadystatechange = this.bind(this, function () {
if (xm.readyState == 4 && xm.status == 200)
this.callback(xm.responseText);
});
if (this.method == "get") {
xm.send();
}
else {
xm.send(this.data);
}
}
}
解决方案 »
- 替换文本中网址,并加上A标签的问题
- JavaScript脚本字符串拆分问题
- 请问这样写有什么意义?
- 为什么window.captureEvents(Event.MOUSEMOVE|Event.MOUSEUP)无效?
- 怎么用JS来实现一个日期型数值加上月份数/天数得到另外一个日期型数值呢?有没有这样的函数?
- 急求兼容IE6
- 打开一个网页时,怎么屏蔽网页“另存为”功能,怎么屏蔽查看IE工具栏中的“查看源代码”功能
- username为空或不是对象?
- 解决马上给分
- 求救!100分,onBlur 控制焦点的问题!!
- 在google和火狐中用jquery获取颜色为rgb,怎么转换成为#CCDDFF这种颜色呢
- 求助此函数,不是很明白。
var _this = this;
this.send = function () {
var xm = new XMLHttpRequest();
_this.url = (data.length > 0 && this.method == "get") ? _this.url + "?" + _this.data : _this.url;
...
}
send函数里面所有this改为_this就行了
var _this = this;
xm.onreadystatechange = function () {
if (xm.readyState == 4 && xm.status == 200)
_this.callback(xm.responseText);
};
这样才行