日期:2014-05-16  浏览次数:20474 次

ajax封装问题,请高手指点
看下面红色代码中的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);
        }
    }
}

------解决方案--------------------
作用域问题
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;
this.send = function () {
        var xm = new XMLHttpRequest();
        _this.url = (data.length > 0 && this.method == "get") ? _this.url + "?" + _thi……