从方法中引用类



我正在编写一个脚本,该脚本应该能够动态加载网页顶栏中多个预定义div中的内容。

在Topbar对象中,Ribbon是一个对象,它包含用于操作Topbar中的一个DIV的函数,其中一些(目前全部)是从Container继承的,其中Ribbon就是其中的一个实例。

函数MPP_Topbar.Ribbon.clear()MPP_Topbar.Ribbon.load('default.xml')按预期工作。然而,一旦xmlhttprequest完成,从ajaxGet()函数调用的回调函数MPP_Topbar.Ribbon.insert()并没有完成它应该做的事情。不知何故,insert类方法中的this突然指向window,而不是它的父对象Ribbon

我有没有办法在insert方法中引用Ribbon


Topbar脚本:

MPP_Topbar = {};
MPP_Topbar.Container = function(){};
MPP_Topbar.Container.prototype.clear = function(){
    var element = this.element;
    while (element.firstChild) {
        element.removeChild(element.firstChild);
    }
};
MPP_Topbar.Container.prototype.load = function(page){
    this.clear();
    ajaxGet(page, this.insert);
    console.log('loading');
};
MPP_Topbar.Container.prototype.insert = function(content){
    console.log(this);
    this.element.innerHTML = content;
    console.log('inserted');
};
MPP_Topbar.Ribbon = new MPP_Topbar.Container;
MPP_Topbar.Ribbon.element = document.getElementById('THERIBBON');

用于AJAX请求的函数:

function ajaxGet(file, callback, postdata, async){
    async = ((async == true || async === undefined) ? true : false);
    var xmlhttp;
    if (window.XMLHttpRequest){
        // code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp=new XMLHttpRequest();
    }
    else{
        // code for IE6, IE5
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
    if(async){
        xmlhttp.onreadystatechange=function(){
            if (xmlhttp.readyState==4 && xmlhttp.status==200){
                callback(xmlhttp.responseText);
            }
        }
    }
    if(postdata){
        xmlhttp.open("POST", file, async);
        xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
    }else{xmlhttp.open("GET", file, async);}
    xmlhttp.send();
}

您需要创建"insert"函数的绑定版本:

ajaxGet(page, this.insert.bind(this));

如果没有该步骤,将调用"insert"函数,以便this引用全局(window)对象。this的值与函数的声明方式或位置无关,而是与函数的调用方式有关。.bind()方法返回一个函数,该函数显式地安排this在调用所需函数时绑定到作为参数传递的对象。

最新更新