0

假设我有一个如下所示的 javascript 类:

var Person = {
    //Private members

    getXmlRequestObj : function() {
            if (window.XMLHttpRequest) {
                return new XMLHttpRequest();
            } else if(window.ActiveXObject) {
                return new ActiveXObject("Microsoft.XMLHTTP");
            } else {
                return "Your Browser needs an upgrade";
            }
        },

initialize: function() {
        Person.importHTML = Person.getXmlRequestObj();
    },


    //Set up the global content retrieval object
    //called importHTML
    //importHTML:  new ActiveXObject("Microsoft.XMLHTTP"),

    _status:'',

    getAjaxList:function(sWhat,sUrl) {
        if (Person.importHTML.readyState == 4 || Person.importHTML.readyState == 0) {
            Person.importHTML.open("GET", sUrl, false);// make it wait for the response
            Person._sWhat = sWhat;
            Person.importHTML.onreadystatechange = Person.handleListArrived; 
            Person.importHTML.send(null);
        }       
    },
     handleListArrived: function() {
        if (Person.importHTML.readyState == 4) {
            if(Person._sWhat=="units")
                Person._unitList = Person.importHTML.responseText;
            if(Person._sWhat=="ranks")
                Person._rankList = Person.importHTML.responseText;
        }
    }
}

而不是使用此代码:

            if(Person._sWhat=="units")
                Person._unitList = Person.importHTML.responseText;
            if(Person._sWhat=="ranks")
                Person._rankList = Person.importHTML.responseText;

我希望它使用任何 Person._sWhat 来成为 Person 的新成员。换句话说,我如何动态地分配 Person 的新成员?从而使代码看起来像这样:

Person.something 的效果 Person._sWhat = Person.importHTML.responseText;

4

2 回答 2

0
getAjaxList:function(sWhat,sUrl) {
    if (Person.importHTML.readyState == 4 || Person.importHTML.readyState == 0) {
        Person.importHTML.open("GET", sUrl, false);// make it wait for the response
        Person.importHTML.onreadystatechange = Person.handleListArrived.bind(Person.importHTML, sWhat); //bind is supported in IE9+
        Person.importHTML.send(null);
    }       
},
handleListArrived: function(sWhat) {
    if (this.readyState == 4) {
        Person[sWhat] = this.responseText;
    }
}

或者,自 ecmascript 1.3 起支持以下内容:

getAjaxList:function(sWhat,sUrl) {
    if (Person.importHTML.readyState == 4 || Person.importHTML.readyState == 0) {
        Person.importHTML.open("GET", sUrl, false);// make it wait for the response
        Person.importHTML.onreadystatechange = function(){ 
            Person.handleListArrived.call(Person.importHTML, sWhat); 
        };
        Person.importHTML.send(null);
    }       
}
于 2013-01-18T19:11:13.507 回答
0

点表示法在 JavaScript 中是一种方便的方式,相当于方括号表示法:

Foo.xyz === Foo['xyz']

所以,在你的情况下

Person[Person._sWhat+"List"] = Person.importHTML.responseText

就足够了,但对于"s"您所在_sWhat领域的尾随。如果您可以在其他地方删除它,那将是理想的。或者:

Person[Person._sWhat.slice(0,-1)+"List"] = Person.importHTML.responseText
于 2013-01-18T19:11:44.870 回答