Question

I've been working with getters and setters to avoid the prospect of using global variables. However, I've run into a problem. The below code, which works fine with integer variables, throws an exception when I try to run an AJAX call instead. Can someone explain to me why this is happening?


function Object_XML() {
    me = this;
    me.xml = null;
}

Object_XML.prototype = {

    getXML: function() {
        return me.xml
    },

    setXML: function(data) {
        me.xml = data;  
    },

    loadXML: function() {
        $.ajax({
            type: "GET",
            url: "questions.xml",
            dataType: "xml",
            success: function(xml) {
                me.setXML(xml);         
            } //close success       
        });//close AJAX 
    }//close setXML

};

$(document).ready(function() {  
    var data = new Object_XML();
    alert("This is an " + data.getXML());
    data.setXML();
    alert("This is an " + data.getXML());
});

Thanks, Elliot Bonneville

Was it helpful?

Solution

You just negated your use of private variables with getters and setters by using me = this; You just made me a global variable by not using var. (any variable not defined using var gets attached to the global namespace)

In your case since you're working within the same object scope you can just use this and avoid the me as personally, i think it's confusing. But if you want to stick to that paradigm, use var me = this;

Your example is really unclear, where does the error happen? You're calling data.setXml() with no parameters, so me.xml will bet set to undefined. That is to be expected if you pass nothing into the method.

Also keep in mind that due to the async nature of your call, if you were to do something like:

data.loadXml();
console.log("data.getXML();", data.getXML());  // would be undefined

data.getXML() at that moment would still be undefined as it's likely your asynchronous call hasn't returned yet, thus not setting the xml attribute of your object.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top