I have a javascript object with a bit of jquery for visual effect.
I can access this.whatever inside the main animate function, but I can’t access this.whatever from the function at the end (when animate is complete)
this.myDiv1 = 'myScrollableDiv';
this.myDiv2 = 'myDivToScrollTo';
this.test = 'It works';
$( "#"+this.myDiv1 ).animate({
scrollTop: $( "#"+this.myDiv2 ).position().top - $( "#"+this.myDiv1 ).position().top
}, 500, function() {
this.myOtherFunction();
});
this.myOtherFunction = function() {
alert(this.test);
};
this.myOtherFunction is not called because I think (this) in the line this.myOtherFunction(); refers to the current jquery animate function and not the global object.
So I have tried creating a copy of (this) as a standard javascript var
var thisCopy = this;
before the animate function, then use thisCopy with all the existing vars. This works…
However, I don’t want to copy (this) because I need to update the real object vars for use with other functions.
I have also tried declaring myOtherFunction as a normal variable, then calling myOtherFunction without the () and it calls the function but still doesn’t give me access to the object vars.
How can I call this.myOtherFunction() after the animation is complete and have access to all of the global object variables?
It seems that you’re concerned that at the time you need the
thisCopyvariable the originalthishas changed and you’re stuck with old data.Well, I have good news:
thisCopyis a shallow copy of the object, not an independent variable. For example:In other words it’s safe to use the
var thisCopy = this;technique.