I have the following javascript object, somewhat pseudocode:
{
dateField: new Date(),
addMinutes:function(numMinutes)
{
CallWebService(numMinutes, function{alert(this.dateField; });
}
}
The problem is the scope of the callback function in CallWebService doesn't see the dateField property of the object. Is there a way I can access it? Thanks!
You need to preserve the context (the this
value) of the addMinutes
function.
There are several ways to achieve it, the most easy one is to simply store a reference of this
on a variable, that variable will be available to the scope of the callback function, e.g.:
var obj = {
dateField: new Date(),
addMinutes: function(numMinutes) {
var instance = this;
CallWebService(numMinutes, function () {
alert(instance.dateField);
});
}
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With