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!