I have about 10 functions in a javascript file. Each function at the beginning has the following statement:
var $me = $(this);
Would it be better to define $me in the global scope and then redefine it at the beginning of each function? Or does it not make any difference? for example…
var $me;
function doo() {$me = $(this)}
function foo() {$me = $(this)}
// etc. etc.
You should NEVER implement your second option with
$medefined globally, but overwritten in each local function. That is a recipe for disaster. If one function calls another (or triggers an event handler),$mewill get overwritten and will get trounced from the proper value in the first function. No – DO NOT DO THIS.The correct way is to define a NEW local variable in each function that you use it in. This is both faster and NOT prone to overwrite errors. FYI, local variables are faster to access than global variables.
If you need a saved copy of $(this) in a function, then put:
near the top of the function (inside the function body) so it’s a temporary local variable.