简体   繁体   中英

JavaScript - using objects and methods?

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

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.

Strange.Its working for me:

http://jsfiddle.net/y5Yk7/

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.

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM