When I call the method getResult it returns an undefined value. What am I doing wrong?
var MyObjectResult = {"Success":1, "Fail":2, "Timeout":3, "None":4}
function MyObject()
{
this.result = MyObjectResult.None;
this.timout = 15;
this.getResult = function ()
{
// Some calculation here and changing result
// Logging (this.result shows that result has value of 1)
this.result = MyObjectResult.Success;
return this.result;
}
}
var myObject = new MyObject();
var result = myObject.getResult();
// result is undefined
console.log(result);
-
1I see nothing wrong with the code above. Could the problem be in the missing calculation code? If you run the above as is does it work for you?nnnnnn– nnnnnn2011年11月30日 04:51:03 +00:00Commented Nov 30, 2011 at 4:51
4 Answers 4
I see nothing wrong with the code as posted, so I'm going to take a guess about what is in the code that you don't show:
Is the missing calculation code doing an ajax request (or some other asynchronous processing) and setting this.result in its success function? If so, the getResult() function will return immediately, before your aysnc processing has run its success or failure function to update this.result. If the logging mentioned in your comment occurs in the success/failure function then it would have the correct value.
Comments
Strange.Its working for me:
1 Comment
(削除) Leaving out the quotes around Success, Fail, Timeout, and None should get it working. (削除ここまで)
I've set up a JSFiddle example; it is working perfectly fine for me.
4 Comments
perhaps 'this' could have a different meaning within your function? so:
var MyObjectResult = {"Success":1, "Fail":2, "Timeout":3, "None":4}
function MyObject()
{
this.result = MyObjectResult.None;
this.timout = 15;
var mythis = this;
this.getResult = function ()
{
mythis.result = MyObjectResult.Success;
return mythis.result;
}
}
var myObject = new MyObject();
var result = myObject.getResult();
2 Comments
this - calling getResult() as a property of myObject will ensure this has the right value within the function.