AJAX 加载与 Getters 和 Setters 结合使用
我一直在使用 getter 和 setter 来避免使用全局变量。但是,我遇到了问题。下面的代码可以很好地处理整数变量,但当我尝试运行 AJAX 调用时会抛出异常。有人可以向我解释为什么会发生这种情况吗?
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());
});
谢谢,埃利奥特·博纳维尔
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您刚刚通过使用
me = this;
否定了对 getter 和 setter 的私有变量的使用 您刚刚通过不使用var
将me
设为全局变量。 (任何未使用 var 定义的变量都会附加到全局命名空间)在您的情况下,由于您在同一对象范围内工作,因此您可以只使用
this
并避免me
就我个人而言,我认为这很令人困惑。但是,如果您想坚持该范例,请使用var me = this;
您的示例确实不清楚,错误发生在哪里?您正在调用不带参数的
data.setXml()
,因此me.xml
将被设置为undefined
。如果您没有向该方法传递任何内容,则这是可以预料的。另请记住,由于您的调用的异步性质,如果您
当时要执行以下操作: data.getXML() 仍将是未定义的,因为您的异步调用可能尚未返回,因此不会设置对象的 xml 属性。
You just negated your use of private variables with getters and setters by using
me = this;
You just mademe
a 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
this
and avoid theme
as 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.xml
will 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.