Whilst using jQuery, I've been using the Object Literal Notation to namespace all of my JavaScript code:
$(document).ready(function() {
var example = {
var1: 1,
var2: 2,
someFunction: function() {
}
};
});
In my function, I wanted to use a jQuery effect, and in that callback, I wanted to reference the variables var1 and var2. Something like so:
$(document).ready(function() {
var example = {
var1: 1000,
var2: 2000,
someFunction: function() {
$('#someId').fadeOut(var1, function() {
alert(var2);
});
}
};
});
The problem with trying something like this, is that you have to use the "this" keyword to reference the variables. However, when you enter the callback function of the jQuery function, the "this" scope is overwritten by jQuery itself, and so you can no longer reference the second variable.
To solve the issue, you simply have to save the scope of the initial "this" and use it in the callback like so:
$(document).ready(function() {
var example = {
var1: 1000,
var2: 2000,
someFunction: function() {
var self = this;
$('#someId').fadeOut(self.var1, function() {
alert(self.var2);
});
}
};
});
Here, I've saved the "this" scope into the variable "self", and the code now works.