使用对象正确替换全局变量
我一直在试图弄清楚如何使用原型初始化对象,以便使用全局变量进行转义,这是我第一次了解 此处。我开始实现在接受的答案中找到的我自己的代码版本。
function XML_Data() {
this.data = null;
}
XML_Data.prototype = {
GetXML: function() {
$.ajax({
type: "GET",
url: "questions.xml",
dataType: "xml",
success: function(xml) {
this.data=xml;
} //close success
});//close AJAX
},
UseXML: function() {
alert(this.data)
}
};
(我的脚本实现)
但是,我遇到了问题。当我使用这段代码运行此处显示的函数时:
var data = new XML_Data();
data.GetXML();
data.UseXML();
我收到一条警告,提示“null”。我已经浏览过这些代码大约十几次了,但由于这是我第一次使用 Javascript,所以很明显我错过了一些东西。你能指出这一点吗?
谢谢,埃利奥特·博纳维尔。
I've been trying to figure out how to initialize an object using a prototype in order to escape using global variables, which I first learned about here. I began implementing my own version of the code found in the accepted answer.
function XML_Data() {
this.data = null;
}
XML_Data.prototype = {
GetXML: function() {
$.ajax({
type: "GET",
url: "questions.xml",
dataType: "xml",
success: function(xml) {
this.data=xml;
} //close success
});//close AJAX
},
UseXML: function() {
alert(this.data)
}
};
(My implementation of the script)
However, I've run into a problem. When I run the functions shown here by using this bit of code:
var data = new XML_Data();
data.GetXML();
data.UseXML();
I get an alert that says "null". I've been through the code about a dozen times, but as this is my first time working with Javascript, there's quite obviously something I've missed. Could you point that out?
Thanks, Elliot Bonneville.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
值得注意的是,
在 Jquery 中发布事件可能会起作用,但我还没有测试过这段代码。
Just of note
Publishing events in Jquery would problably work,but I havent tested this code.
您现在拥有的代码尝试使用非阻塞异步 API 同步(按顺序)运行。 UseXML 调用发生在 GetXML 调用实际完成其 AJAX 操作之前,因为它是异步的。
您可以以异步模式(其中在 AJAX 请求成功时直接调用 this.UseXML)或同步模式(其中将“async:false”传递给 AJAX 调用)编写此代码。异步模式在 JavaScript 开发中更为常见,因为它更强大,同步请求通过阻止脚本执行来阻止浏览器中的 UI,但同步对于小事情来说更容易做到。
请参阅 http://api.jquery.com/jQuery.ajax/
The code you have now is attempting to run synchronously (in order) using a non-blocking asynchronous API. The UseXML call happens before the GetXML call actually finishes doing its AJAX thing, because it's asynchronous.
You could write this in an asynchronous pattern (in which this.UseXML is called directly on success of the AJAX request), or a synchronous pattern (in which "async:false" is passed to the AJAX call). The asynchronous pattern is much more common in JavaScript development, as it is much more powerful, and synchronous requests block the UI in the browser by preventing script execution, but synchronous is much easier to do for little things.
See http://api.jquery.com/jQuery.ajax/