0

I am building an app in JavaScript. I am trying to get my head around how to use this in a JavaScript closure. Currently, I have the following code:

var ExternalResource = require('ExternalResource');
function MyObject() {
}

MyObject.prototype.state = "Closed";
MyObject.prototype.execute = function(options, callback) {
  if (!options) {
    if (callback) {
      callback(-1);
    }
    return;
  }

  try {
    this.state = 'Connecting';
    var client = new ExternalResource.Client();
    client.connect(function(err) {
      if (err) {
        this.state = 'Failed';
        if (callback) {
          callback(-1, err);
        }
      } else {
        this.state = 'Good';
        if (callback) {
          callback(1);
        }
      }
    });
  } catch (ex) {
    if (callback) {
      callback(-1, ex);
    }
  }
};

I am currently executing execute by a Jasmine test.

it(' - Connect to a local instance', function(done) {
  var myObject = new MyObject();
  myObject.execute({}, function() {
    expect(myObject.state).toBe('Good');
  });
});

When this test gets executed, I see the following error:

Expected 'Connecting' to be 'Good'.

I am sure it has something to do with using this.state in the connect callback. Yet, I'm not certain.

Thank you!

JQuery Mobile
  • 6,221
  • 24
  • 81
  • 134

1 Answers1

1

you should create a _self reference into the outer scope so you can properly use it in the inner scope

...
var _self = this;
client.connect(function(err) {
  if (err) {
    _self.state = 'Failed';
    if (callback) {
      callback(-1, err);
    }
  } else {
    _self.state = 'Good';
    if (callback) {
      callback(1);
    }
  }
  ...
Fabrizio Calderan
  • 120,726
  • 26
  • 164
  • 177