保持说没有定义结果属性。 为什么?

这是我的对象,我已经定义了所有的属性和function,但它仍然给我这个错误result is not defined

这是我的代码

 var Xml = { to : null, from : null, url : null, result : null, //<--- I defined result here init: function (fromaddress, toaddress, link) { from = fromaddress; to = toaddress; url = link; this.requestXml(); return this; }, requestXml: function () { $.ajax({ type: "GET", url: url, dataType: "xml", success: this.parseXml }); }, parseXml: function (xml) { console.log('xml: ' + $(xml)); result = $(xml); //<--- Assigning value to result here }, getResult: function () { console.log('Result: ' + result); // <--- Here is says result is not defined return result; } }; 

我怎么解决这个问题?

更新

我在下面调用getResult()

 var Route = { fromurl : null, tourl : null, from : null, to : null, init: function (fromaddress, toaddress) { from = fromaddress; to = toaddress; fromurl = 'http://demo.com/url'+fromurl; tourl = 'http://demo.com/url'+tourl; Route.searchRoute(); }, searchRoute: function () { var xml = Xml.init(from, to, fromurl); console.log(xml.getResult()); //<---- calling getResult(); } }; 

“未修饰”的表达式result将引用一个名为result的全局变量,这是您没有的。

假设仅仅因为对result的引用在文本上是在对象内部引用引用该对象的属性是不正确的。 在其他语言中可能就是这种情况,但在JavaScript中则不然。

您问题的解决方案是对问题的评论之一。 用this. 作为前缀适用于这些情况。 试试这段代码:

 var x = 1; var p = { x: 2, f: function () {alert(x); alert(this.x);} } pf(); 

在这里你会看到1提醒然后2。

回答更新的问题

你在这里有一个经典的问题。 你写

 var xml = Xml.init(from, to, fromurl); console.log(xml.getResult()); //<---- calling getResult(); 

第一行最终触发了Ajax请求。 一旦该请求被触发,您立即转到第二行,在那里调用xml.getResult()您的Ajax调用能够填充result之前,getResult的调用将会发生几乎100%的result

一种方法是将您想要对结果执行的操作传递给init方法。 在这种情况下,您似乎想要记录结果,请尝试

 var xml = Xml.init(from, to, fromurl, function () {console.log(xml.getResult()}); 

这里我们有一个新的第四个参数到Xml.init所以我们必须通过更新Xml对象来处理它,就像这样(未经测试):

 . . . init: function (fromaddress, toaddress, link, callback) { from = fromaddress; to = toaddress; url = link; this.requestXml(callback); return this; }, requestXml: function (callback) { $.ajax({ type: "GET", url: url, dataType: "xml", success: callback }); }, . . . 

换句话说,当您打算进行异步调用时,立即使用结果。 不要把它们保存起来以备日后使用,因为你永远都不知道它们什么时候会“准备好”。

您应该使用this ,但如果您使用构造函数可能会更容易,因此您可以访问所有方法中的属性:

 function Xml(to, from, url, result) { this.to = to || null; this.from = from || null; this.url = url || null; this.result = result || null; // init logic } Xml.prototype = { parseXml: function (xml) { console.log('xml: ' + $(xml)); this.result = $(xml); }, getResult: function () { console.log('Result: ' + this.result); return this.result; } ... } var xml = new Xml(to, from, url, result); // init 

编辑:对象文字可能不是最佳选择。 您的情况更适合上面的构造函数,或者如果您想避免this混淆,则更适合模块模式:

 function Xml() { var xml = {} , to = null , from = null , url = null , result = null; xml.parseXml = function( xml ) { ... }; ... return xml; } var xml = Xml(); 

尝试XML.result

请参阅在Javascript中理解“this”,以了解此问题的细节以及它指向不同时间的内容。