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
You just negated your use of private variables with getters and setters by using
me = this;You just mademea global variable by not usingvar. (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
thisand avoid themeas personally, i think it’s confusing. But if you want to stick to that paradigm, usevar me = this;Your example is really unclear, where does the error happen? You’re calling
data.setXml()with no parameters, some.xmlwill bet set toundefined. 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.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.