Here is my object and I have defined all the properties and functions but it still gives me this error result is not defined.
Here is my code
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;
}
};
How can I solve this problem?
Update
I am calling getResult() below
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();
}
};
The “undecorated” expression
resultwould refer to a global variable namedresult, which you do not have.It is not correct to assume that just because a reference to
resultis textually inside of an object that the reference refers to a property of that object. That may be the case in other languages, but not in JavaScript.The solution to your problem is in one of the comments to the question. Using
this.as a prefix works in these cases. Try this code:Here you will see 1 alerted and then 2.
Answer to updated question
What you have here is a classic problem. You write
The first line eventually fires of an Ajax request. Once that request is fired off, you immediately go to your second line, where you call
xml.getResult(). Chances are nearly 100% that the call togetResultwill happen before your Ajax call is able to fill in the value ofresult.One approach is to pass the thing you want to do with the result to the
initmethod. In this case it looks like you want to log the result, so tryHere we have a new fourth parameter to
Xml.initso we have to handle that by updating theXmlobject, like so (not tested):In other words, when you are going to make asynchronous calls, consume the results right away. Don’t save them away for later, because you never know when they are going to be “ready”.