Lately a lot of my code has been looking like this...
function MyObjectClass (selector) {
this.color = "red";
this.$elt = $(selector);
// ... any other object vars here ...
// Example method for the object
this.showThenUpdateColor = function () {
// Keep a copy of "this" to use for callbacks
var o = this;
// Example of jQuery function that accepts a callback
o.$elt.fadeIn(function(){
// Inside of this callback function we need to access the main object
o.$elt.css({
"background-color" : o.color // This is where we need the "o"
});
});
}
}
var myObject = new MyObjectClass('#myObject');
myObject.showThenUpdateColor();
...where I have a callback inside of an object method. Typically I assign the object itself ("this") to a local variable (usually "o" because it's short and easy) which can be used in the callback.
Is this an optimal use of memory? Is there any danger of memory leaks? Is there a better way?